Mark Boulder
Mark Boulder

Reputation: 14277

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") %>

Upvotes: 7

Views: 3975

Answers (2)

mu is too short
mu is too short

Reputation: 434635

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.

Upvotes: 3

M. Cypher
M. Cypher

Reputation: 7066

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

Upvotes: 3

Related Questions