Minimal template engine with default escaping.
Herb is a fork of Mote that uses a ERB-like style syntax and auto-escape HTML special characters by default.
Add this line to your application's Gemfile:
gem "herb"And then execute:
$ bundle
Or install it yourself as:
$ gem install herb
This is a basic example:
require "herb"
template = Herb.parse("your template goes here!")
template.call
# => "your template goes here!"Herb recognizes two tags to evaluate Ruby code: <% %>, and <%= %>. The difference between them is that while the <% %> tags only evaluate the code, the <%= %> tags also prints the result to the template.
Imagine that your template looks like this:
<% # single line code %>
<% gems = ["rack", "cuba", "herb"] %>
<%
# multi-line code
sorted = gems.sort
%>
<ul>
<% sorted.each do |name| %>
<li><%= name %></li>
<% end %>
</ul>The generated result will be like:
<ul>
<li>cuba</li>
<li>herb</li>
<li>rack</li>
</ul>The values passed to the template are available as local variables:
template = Herb.parse("Hello {{ name }}", [:name])
template.call(name: "Ruby")
# => Hello RubyYou can also use the params local variable to access the given parameters:
template = Herb.parse("Hello {{ params[:name] }}")
template.call(name: "Ruby")
# => Hello RubyBy default, Herb escapes HTML special characters to prevent XSS attacks. You can start the expression with an exclamation mark to disable escaping for that expression:
template = Herb.parse("Hello {{ name }}", [:name])
template.call(name: "<b>World</b>")
# => Hello <b>World<b>
template = Herb.parse("Hello {{! name }}", [:name])
template.call(name: "<b>World</b>")
# => Hello <b>World</b>There's a helper available in the Herb::Helpers module, and you are
free to include it in your code. To do it, just type:
include Herb::HelpersThe herb helper receives a file name and a hash and returns the rendered version of its content. The compiled template is cached for subsequent calls.
herb("test/basic.erb", n: 3)
# => "***\n"When the herb helper is first called with a template name, the file is read and parsed, and a proc is created and stored in the current thread. The parameters passed are defined as local variables in the template. If you want to provide more parameters once the template was cached, you won't be able to access the values as local variables, but you can always access the params hash.
For example:
# First call
herb("foo.erb", a: 1, b: 2)Fork the project with:
$ git clone git@github.com:frodsan/herb.git
To install dependencies, use:
$ bundle install
To run the test suite, do:
$ rake test
For bug reports and pull requests use GitHub.
Herb is released under the MIT License.