Rails I18n: Better way of interpolating links?

戏子无情 提交于 2019-12-22 05:52:28

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/12334183/rails-i18n-better-way-of-interpolating-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!