Tilt::Handlebars

Gem Version Build Status Test Coverage Maintainability MIT License

A Tilt interface for the official JavaScript implementation of the Handlebars.js template engine.

Handlebars::Engine provides the API wrapper. MiniRacer provides the JavaScript execution environment.

See Handlebars.js for template syntax.

See Handlebars::Engine for API syntax.

Installation

Add this line to your application's Gemfile:

gem 'tilt-handlebars'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install tilt-handlebars

Usage

Create a Handlebars template file with either a .hbs or .handlebars extension.

Example, in hello.hbs:

Hello, {{name}}. I'm {{emotion}} to meet you.

Then, render the template with Ruby:

require 'tilt/handlebars'

template = Tilt.new('hello.hbs')
puts template.render(nil, name: "Joe", emotion: "happy")

Output:

Hello, Joe. I'm happy to meet you.

Partials

Partials are a file that can be loaded into another. For example, you may define a web page with a master layout (layout.hbs), which includes a header (header.hbs) and footer (footer.hbs). In this case, header.hbs and footer.hbs would be partials; layout.hbs includes these partials.

layout.hbs:

<html>
    <head>...</head>
    <body>
        {{> header }}

        {{ content }}

        {{> footer }}
    </body>
</html>

Notice that you do not include the .hbs file extension in the partial name. Tilt Handlebars will look for the partial relative to the enclosing file (layout.hbs in this example) with either a .hbs or .handlebars extension.

Sinatra

Handlebars can be used with Sintra:

require 'sinatra/handlebars'

class MyApp < Sinatra::Base
  helpers Sinatra::Handlebars

  get "/hello" do
    handlebars :hello, locals: {name: 'Joe'}
  end
end

This will use the template file named views/hello.hbs.

Partials can also be used with Sinatra. As described previously, partials will be loaded relative to the enclosing template (e.g., in the views directory).

Changelog

See RELEASE_NOTES.md for more details.

Contributing

Bug reports and pull requests are welcome on GitHub: https://github.com/gi/tilt-handlebars.

See CONTRIBUTING.md for more details.

License

The gem is available as open source under the terms of the MIT License.