ZK Zhao
ZK Zhao

Reputation: 21513

Rails: Is it possible to show different content based on I18N?

Not just text.

For example, I may want to display a button when the language is Chinese, and hide it when the language is English.

My thought :, in controller, make the I18N accesible through view, maybe something like @I18n = I18n.locale

Upvotes: 2

Views: 272

Answers (2)

Sean Xiao
Sean Xiao

Reputation: 616

Option 1: check locale in the controller/view (preferably in controller) and render conditionally;

Option 2: put the button's HTML inside the locale dictionary

# config/locales/zh-CN.yml
zh-CN:
  welcome_html: <button>欢迎</button>      
  goodbye:
    html: <button>再见</button>

From the official documentation:

Keys with a '_html' suffix and keys named 'html' are marked as HTML safe. When you use them in views the HTML will not be escaped.

Read more here: http://guides.rubyonrails.org/i18n.html

Upvotes: 1

Max Williams
Max Williams

Reputation: 32933

You can always inspect the value of the current locale setting with I18n.locale. So you can hang the test off that:

<% if I18n.locale =~ /^zh/ %>
  <!-- button code -->
<% end %>

Note i'm testing against any Chinese locale here, which afaik all start with "zh"

Upvotes: 2

Related Questions