Skip to content

Commit

Permalink
Allow nested interpolations
Browse files Browse the repository at this point in the history
  • Loading branch information
iGEL committed Jul 16, 2011
1 parent cabb6af commit e21164e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
7 changes: 7 additions & 0 deletions README.textile
Expand Up @@ -43,6 +43,13 @@ You may also specify options for @link_to@. Just give a second option named like
You may pass any kind of object accepted by @link_to@ as the link target, so your loved named routes like
@article_path(:id => article.id)@ or hashes like @{controller: "articles", action: "index"}@ will all work fine, too.

Even nested interpolations are possible:

<pre><code>en:
copy: "Did you read this %{link:nice %{guide}}?"</code></pre>

<pre><code><%=t_link "copy", link: "http://guides.rubyonrails.org/i18n.html", guide: 'article' %></code></pre>

h2. isit18.com?

Sorry, I'm using Ruby 1.9.2 at the time of writing and didn't took the time to port i18n_link back to Ruby 1.8. You either might update to Ruby 1.9 as well
Expand Down
21 changes: 18 additions & 3 deletions lib/i18n_link/helper.rb
Expand Up @@ -7,22 +7,37 @@ module Helper

def t_link(translation, options = {})
options.symbolize_keys!
string = h(t(translation)).gsub(/%\{[^}]+\}/) do |tl|
string = String.new(h(t(translation))) # We want an escaped String, not an ActiveSupport::SafeBuffer

# Resolve the inner interpolations of nested interpolations
string.gsub!(/(%\{[^}]+:[^}]*)(%\{[^}]+\})([^}]*\})/) do |tl|
token = $2[2..-2].to_sym
if options.has_key?(token)
"#{$1}#{options[token]}#{$3}"
else
tl
end
end

# Parse links
string.gsub!(/%\{[^}]+\}/) do |tl|
if tl.include?(":")
token, label = tl[2..-2].split(":", 2)
addr = options.delete(token.to_sym)
if addr.nil?
tl
else
link_options = options.delete("#{token}_options".to_sym)
link_to(label, addr, link_options)
link_to(raw(label), addr, link_options)
end
else
tl
end
end

# Escape HTML of the replacements and interpolate
options.each { |key, value| options[key] = (value.is_a?(String) && !value.html_safe?) ? h(value) : value }
raw(string % options)
end
end
end
end
7 changes: 6 additions & 1 deletion spec/i18n_link_helper_spec.rb
Expand Up @@ -62,4 +62,9 @@
I18n.backend.store_translations(:en, :test5 => "Hello %{name}.")
@view.t_link("test5", :name => '<a href="http://www.rubyonrails.org">Rails</a>'.html_safe).should == 'Hello <a href="http://www.rubyonrails.org">Rails</a>.'
end
end

it "should allow interpolations inside of links" do
I18n.backend.store_translations(:en, :test6 => "Did you read our %{link:nice %{article}}?")
@view.t_link("test6", :link => "/article/2", :article => "article").should == 'Did you read our <a href="/article/2">nice article</a>?'
end
end

0 comments on commit e21164e

Please sign in to comment.