当前位置: 动力学知识库 > 问答 > 编程问答 >

Can you change label display names when using simple-form in rails?

问题描述:

I am using simple-form in rails and I would like to know if there is a way to change the way collection objects are displayed. For example I have something like this

<%= f.input :lang, :label => "Language", :collection => [ "en", "es, "zh", "fr" ] %>

Instead of showing up as "en es zh" etc I would like it to show up as "English Spanish" etc to the user. Is there anyway to do that sort of thing?

Thanks in advance.

网友答案:

You can use following way as well:

In Model:

    LANGUAGES = {'English' => 'en','French' => 'fr'}

In View:

    <%= f.input :lang, :label => "Language", :collection => Model::LANGUAGES %>
网友答案:

I guess that the label will be "English" and the value "en"; you can do something like this:

Store the data in a Model (recommended) or make a hash:

@data = Language.all

In the view use label_method and value_method:

<%= f.input :lang, :label => "Language", :collection => @data, :label_method => :name, :value_method => :value %>

Check the section Collections in https://github.com/plataformatec/simple_form

网友答案:

Another option is to add a helper

def languages_display
  [
    ["English", "en"],
    ["Spanish", "sn"],
    ["French", "fr"],
  ]
end

And then call your helper from the input field:

<%= f.input :state, :collection => languages_display %>

And then on your show view you could call the following helper so that it displays English and not the en you have in the db:

def show_language(language)
  {
    "en" => 'English',
    "sp" => 'Spanish',
    "fr" => 'French'
  }[language]
end
网友答案:

My approach is to put entire collection in locale yml file (en.yml):

#RAILSROOT/locales/en.yml
en:
  collections:
    languages: 
      - - en
        - English
      - - de
        - Deutch

and in view just write:

<%= f.input :lang, :label => "Language", :collection => t("collections.languages") %>

I use this A LOT so I even wrote gem with helper functions which extends I18n (https://github.com/rstgroup/i18n-structure) and with that in gemfile you can write (notice "tc" helper)

<%= f.input :lang, :label => "Language", :collection => tc(:languages) %>
网友答案:
 <%= f.input :lang, label: "Language", collection: [ [ "English", "en" ], [ "Spanish", "es" ], [ "French", "fr" ] ] %>

This works above, use a nested array. Also, this was used in the latest rails and simple form.

分享给朋友:
您可能感兴趣的文章:
随机阅读: