如何在选择字段中添加基于条件的选定状态

时间:2016-07-20 05:52:07

标签: ruby-on-rails slim-lang ruby-on-rails-5

选择字段:

select#language_top onChange="window.location.href=this.value"
  option value=("#{url_for(locale: 'en')}") data-image=("#{image_url('english.png')}") English
  option value=("#{url_for(locale: 'de')}") data-image=("#{image_url('german.png')}") selected='' German

我想根据条件添加selected=''。我这样做了:

select#language_top onChange="window.location.href=this.value"
  - if params[:locale] == "en"
    option value=("#{url_for(locale: 'en')}") data-image=("#{image_url('english.png')}") selected='' English
  - else
    option value=("#{url_for(locale: 'en')}") data-image=("#{image_url('english.png')}") English
  - if params[:locale] == "de"
    option value=("#{url_for(locale: 'de')}") data-image=("#{image_url('german.png')}") selected='' German
  - else
    option value=("#{url_for(locale: 'de')}") data-image=("#{image_url('german.png')}") German

我认为它可以重构。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这应该适合你:

select#language_top onChange="window.location.href=this.value"
  option selected=(params[:locale] == "en") value=("#{url_for(locale: 'en')}") data-image=("#{image_url('english.png')}") English
  option selected=(params[:locale] == "de") value=("#{url_for(locale: 'de')}") data-image=("#{image_url('german.png')}") German