V1.3: Templates


A template is a file that contains a body for a specific format of a multipart email. For instance, welcome.html.erb describes the markup of the HTML part of the message, while welcome.txt.erb is for the textual part.

It is rendered by bounding the context of a mailer and using a template engine.


For convenience, there is a correlation between the view mailer name and the template file name. It’s the translation of the name into a path: from Mailers::ForgotPassword to forgot_password.

The remaining part is made of multiple file extensions. The first is relative to the format and the latter is for the template engine.

Hanami only accepts :html and :txt formats for emails.

For a given mailer named Mailers::ForgotPassword, there must be at least one template forgot_password.[format].[engine] under the mailers templates directory.

Custom Template

If we want to associate a different template to a mailer, we can use template.

# lib/bookshelf/mailers/forgot_password.rb
module Mailers
  class ForgotPassword
    include Hanami::Mailer
    template 'send_password'

Our view will look for lib/bookshelf/mailers/templates/send_password.* template.


Hanami looks at the last extension of a template file name to decide which engine to use (eg welcome.html.erb will use ERb). The builtin rendering engine is ERb, but Hanami supports countless rendering engines out of the box.

This is a list of the supported engines. They are listed in order of higher precedence, for a given extension. For instance, if ERubis is loaded, it will be preferred over ERb to render .erb templates.

Engine Extensions
Erubis erb, rhtml, erubis
ERb erb, rhtml
Redcarpet markdown, mkd, md
RDiscount markdown, mkd, md
Kramdown markdown, mkd, md
Maruku markdown, mkd, md
BlueCloth markdown, mkd, md
Asciidoctor ad, adoc, asciidoc
Builder builder
CSV rcsv
CoffeeScript coffee
WikiCloth wiki, mediawiki, mw
Creole wiki, creole
Etanni etn, etanni
Haml haml
Less less
Liquid liquid
Markaby mab
Nokogiri nokogiri
Plain html
RDoc rdoc
Radius radius
RedCloth textile
Sass sass
Scss scss
Slim slim
String str
Yajl yajl

In order to use a different template engine we need to bundle the gem and to use the right file extension.

# lib/bookshelf/mailers/templates/welcome.html.haml
%h1 Welcome

Templates Directory

Templates are located in the default directory mailers/templates, located under an application’s directory lib/bookshelf, where bookshelf is the name of our application. If we want to customize this location, we can set a different value in Hanami::Mailer configuration.

# lib/bookshelf.rb
# ...

Hanami::Mailer.configure do
  # ...
  root 'path/to/templates'

The application will now look for templates under path/to/templates.