florian
florian

Reputation: 1001

Rails i18n check if an item exists before display

I have a basic loop to display items from an i18n list:

  <% t('.items').each do |item| %>
    <p><%=item[:description]%></p>
    <p><%=item[:description_html]%></p>
  <%end%>

my .yml file is organized as follow:

fr:
  pages:
    index:
      items:
      - title: The title
        description: The description 
        description_html: <p> The description with HTML tags</p>

Sometimes, the item description_html doesn't have any value in my .yml i18n file, so I would like to check first in my code if description_html has value before displaying it in my HTML. Any suggestion?

Thanks !

Upvotes: 1

Views: 2289

Answers (1)

Shadwell
Shadwell

Reputation: 34784

If you just want to test whether a translation is available you can use I18n.exists?

For example:

<% if I18n.exists?('pages.index.items.description_html') %>
  <%= I18n.t('pages.index.items.description_html') %>
<% end %>

If you do just want to display some default output when there is no translation you can add a default as per this answer with:

<%= I18n.t('pages.index.items.description_html', default: 'No description') %>

Upvotes: 4

Related Questions