Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails I18n: Better way of interpolating links?

Is there a cleaner, content_tag-ish way of doing this? (I don't want HTML in my YML)

en.yml:

expert_security_advice: "Go <a href='{{url}}'>here</a> for expert security advice."

layout.html.erb:

<%= t(:expert_security_advice, :url => "http://www.getsafeonline.org") %>
like image 667
Mark Boulder Avatar asked Sep 08 '12 20:09

Mark Boulder


2 Answers

The best I could come up with:

en.yml:

expert_security_advice: "Go *[here] for expert security advice."

layout.html.erb:

<%= translate_with_link(:expert_security_advice, "http://www.getsafeonline.org") %>

application_helper.rb:

include ActionView::Helpers::TagHelper

def translate_with_link(key, *urls)
  urls.inject(I18n.t(key)) { |s, url|
    s.sub(/\*\[(.+?)\]/, content_tag(:a, $1, :href => url))
  }
end
like image 57
M. Cypher Avatar answered Oct 16 '22 10:10

M. Cypher


No, there isn't a cleaner way of dealing with this. If you want pull the url out of the string then you're stuck breaking the sentence into four pieces:

  1. "Go.
  2. <a href="{{url}}">...</a>
  3. 'here'
  4. 'for expert security advice.'

These four pieces are easy to put back together in English but the order might change in other languages and that can change the capitalization of here and cause other problems. To get it right, you'd have to structure things like this:

here        = "<a href=\"#{url}\">#{t(:expert_security_advice_here)}</a>"
whole_thing = t(:expert_security_advice, :here => here)

and the two separate strings in your YAML:

expert_security_advice_here: "here"
expert_security_advice: "Go {{here}} for expert security advice."

You'd also have to tell the translators that those two pieces of text go together.

If that sort of thing seems cleaner to you then go for it but I wouldn't worry about small bits of HTML in text that needs to be translated, any translator worth talking to will be able to handle it. Never try to take shortcuts with I18N/L10N issues, they will always lead you astray and cause problems: non-DRY code (WET code?) is always better than broken code.


As an aside, I'd recommend that you drop the standard Rails I18N string handling tools in favor of gettext, keeping everything synchronized with gettext is much easier and the code ends up being much easier to read.

like image 24
mu is too short Avatar answered Oct 16 '22 12:10

mu is too short