Question

I'd like to have a small dropdown menu where users can select the website's language. For that, I have

<%= f.select(:lang, options_for_select([%w(中文 ch), %w(English en), %w(日本語 jp), %w(한국어 kr)], 'en')) %>

I'd like this to appear on all pages, and I don't think it's necessary to have that stored in a model, so I was thinking of making it with virtual attribtues.

I'm just a bit confused as to where/how I should make this virtual attribute :lang so that the dropdown appears on all pages and the language persists throughout the users' visit to the webpage. Should I make a getter/setter method in my application_controller.rb?

Thanks!

Était-ce utile?

La solution

Something that appears on many pages that you only want to define once is often defined as a helper.

app/helpers/application_helper.rb

class ApplicationHelper
  def language_select
    form_for :language, :url => some_path do |form|
      form.select(:lang, options_for_select([%w(中文 ch), %w(English en), %w(日本語 jp), %w(한국어 kr)], 'en'))
    end
  end
end

In your views then:

<%= language_select %>

Autres conseils

You can store lang attribute to session. use ajax to store user's selection.

in your page:

<%=select_tag(:lang, options_for_select([%w(中文 ch), %w(English en), %w(日本語 jp), %w(한국어 kr)], session[:lang]||'en'))%>

<script type="text/javascript">
$('#lang').change(function(){
  $.ajax({
    url: "languages/select",
    type: "GET",
    data: {'value=' + $('#lang').val() },
  })
});
</script>

in app/controllers/languages_controller.rb

def LanguagesController
  def select
    session[:lang] = params[:value]

    render js: ''
  end
end

in config/route.rb, make sure you have:

get "languages/select"

Javascript uses JQuery ,it seems like you are using Rails 4, it should work.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top