Module: LocaleSelector::ViewInstanceMethods

Defined in:
lib/locale_selector.rb

Instance Method Summary collapse

Instance Method Details

#language_selector(additional_params = params, &block) ⇒ Object

Simple text based UI element for locale/language selection, that you can put on every page by calling this method in your layout view. Lists the languages offered by application as clickable links. see also #offer_locales.

You can provide a block (executed per language) if you would like to override the default list of text based <a href=“”> elements.

For example, you can easily implement an image based language selector language_selector do |lang, active|

link_to image_tag("#{lang}#{active ? '' : '_inactive'}.png", :alt => lang),
  language_selector_href(lang, params)

end



194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/locale_selector.rb', line 194

def language_selector(additional_params=params, &block)
   :ul, :id => 'language_selector' do
    offered_locales.map do |lang|
      selected = lang == effective_locale
       :li, :class => "#{lang} #{selected ? 'selected' : ''}" do
        if block_given?
          yield lang, selected
        else
          link_to(lang, language_selector_href(lang, additional_params))
        end
      end
    end.join
  end
end

#language_selector_href(lang, params) ⇒ Object

Can be used if you are going to implement your own language selection control. Generates a link, that links to the current page but with an additional ‘lang’ parameter.

Note: if the user fills in e.g. form fields and clicks the language selection link afterwards, then the filled in data is lost.



215
216
217
218
219
220
# File 'lib/locale_selector.rb', line 215

def language_selector_href(lang, params)
  path = (uri = request.request_uri) ? uri.split('?').first.to_s : ''
  q = request.query_parameters.merge({'lang' => "#{lang}"}).map {
    |k,v| "#{URI.escape(k.to_s)}=#{URI.escape(v.to_s)}" }.sort.join("&amp;")
  "#{path}?#{q}"
end