I\'d like to i18n a text that looks like this:
Already signed up? Log in!
Note that there is a link on the text. On this example
We had the following:
module I18nHelpers
def translate key, options={}, &block
s = super key, options # Default translation
if block_given?
String.new(ERB::Util.html_escape(s)).gsub(/%\|([^\|]*)\|/){
capture($1, &block) # Pass in what's between the markers
}.html_safe
else
s
end
end
alias :t :translate
end
or more explicitly:
module I18nHelpers
# Allows an I18n to include the special %|something| marker.
# "something" will then be passed in to the given block, which
# can generate whatever HTML is needed.
#
# Normal and _html keys are supported.
#
# Multiples are ok
#
# mykey: "Click %|here| and %|there|"
#
# Nesting should work too.
#
def translate key, options={}, &block
s = super key, options # Default translation
if block_given?
# Escape if not already raw HTML (html_escape won't escape if already html_safe)
s = ERB::Util.html_escape(s)
# ActiveSupport::SafeBuffer#gsub broken, so convert to String.
# See https://github.com/rails/rails/issues/1555
s = String.new(s)
# Find the %|| pattern to substitute, then replace it with the block capture
s = s.gsub /%\|([^\|]*)\|/ do
capture($1, &block) # Pass in what's between the markers
end
# Mark as html_safe going out
s = s.html_safe
end
s
end
alias :t :translate
end
then in ApplicationController.rb just
class ApplicationController < ActionController::Base
helper I18nHelpers
Given a key in the en.yml
file like
mykey: "Click %|here|!"
can be used in ERB as
<%= t '.mykey' do |text| %>
<%= link_to text, 'http://foo.com' %>
<% end %>
should generate
Click here!