Search code examples
ruby-on-rails-3i18n-gem

Use translation for submit button


I don't want to use the default

<%= f.submit %>

and have created a helper function for it, which also embeds an icon. The helper function expects a label to put on the newly created button.

I'm calling it like this:

<%= submit_button("icon-plus", I18n.translate("helpers.submit.create")) %>

But now on this text appears on the button:

%{model} toevoegen

Instead of:

Product type toevoegen

If I use the normal submit button then the correct text appears so my yml files are correct. How can I get the correct text to use in the helper?

Helper code:

def submit_button(icon, label)
  link_to "javascript:void(0)", :class => 'btn btn-primary', :onclick => "$(this).closest('form').submit()" do
  raw('<div class="') + icon + raw(' icon-white"> ') + label +raw('</div>')
  end
end

Solution

  • As the I18n guide says, the translate function interpolates variables passed in the %{} brackets using its second argument (a hash).

    In your case you need to tell it the model by doing this:

    I18n.t("helpers.submit.create", model: "Product type")
    

    If you want a generic option that would work for any model, you can see how Rails itself does it by looking at the source on GitHub - it's something like

    I18n.t("helpers.submit.create", model: f.object.class.model_name.human)
    

    As an aside, you don't need to (and probably shouldn't) use raw there. What you are trying to achieve could easily be done with the built-in helpers:

    link_to ... do
      content_tag :div, label, class: "#{icon} icon-white"
    end