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") %>
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
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:
"Go
.<a href="{{url}}">...</a>
'here'
'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With