Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active September 22, 2019 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/6f3087e2d2b6dfce9367c061aecd5f54 to your computer and use it in GitHub Desktop.
Save JoshCheek/6f3087e2d2b6dfce9367c061aecd5f54 to your computer and use it in GitHub Desktop.
Just playing. Gives `gettext` its own HTML tags.
# Just playing (based on https://twitter.com/tenderlove/status/1175527260671107072)
require 'nokogiri'
require 'erb'
require 'gettext'
class ErbHtml
include GetText # I have no dea how to use this gem :shrug:
# Based on their example: https://github.com/ruby-gettext/gettext/blob/2fae9e520a578df4d5716712fd8b78953f4076f3/lib/gettext.rb#L184
LOCALIZATION = {
apples: ["Apple", "%{num} Apples"],
bananas: ["Banana", "%{num} Bananas"],
kiwis: ["Kiwi", "%{num} Kiwis"],
}
def initialize(template)
@erb = ERB.new(template, trim_mode: '-<>')
end
def render(bnd)
doc = Nokogiri::HTML.fragment @erb.result bnd
doc.css('n_').each do |element|
num = element.inner_text.to_i
key = element['key'].intern
str = n_(LOCALIZATION.fetch(key), num) % { num: num }
element.replace str
end
doc.to_html
end
end
fruits = {apples: 3, bananas: 1, kiwis: 13}
ErbHtml.new(<<~HTML).render(binding)
<ul>
<% fruits.each do |fruit, quantity| -%>
<li>
<n_ key="<%= fruit %>">
<%= quantity %>
</n_>
</li>
<% end %>
</ul>
HTML
# => "<ul>\n" +
# " <li>\n" +
# " 3 Apples\n" +
# " </li>\n" +
# " <li>\n" +
# " Banana\n" +
# " </li>\n" +
# " <li>\n" +
# " 13 Kiwis\n" +
# " </li>\n" +
# " \n" +
# "</ul>\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment