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.

Naming

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.

  1. # lib/bookshelf/mailers/forgot_password.rb
  2. module Mailers
  3. class ForgotPassword
  4. include Hanami::Mailer
  5. template 'send_password'
  6. end
  7. end

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

Engines

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.

EngineExtensions
Erubiserb, rhtml, erubis
ERberb, rhtml
Redcarpetmarkdown, mkd, md
RDiscountmarkdown, mkd, md
Kramdownmarkdown, mkd, md
Marukumarkdown, mkd, md
BlueClothmarkdown, mkd, md
Asciidoctorad, adoc, asciidoc
Builderbuilder
CSVrcsv
CoffeeScriptcoffee
WikiClothwiki, mediawiki, mw
Creolewiki, creole
Etannietn, etanni
Hamlhaml
Lessless
Liquidliquid
Markabymab
Nokogirinokogiri
Plainhtml
RDocrdoc
Radiusradius
RedClothtextile
Sasssass
Scssscss
Slimslim
Stringstr
Yajlyajl

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

  1. # lib/bookshelf/mailers/templates/welcome.html.haml
  2. %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.

  1. # lib/bookshelf.rb
  2. # ...
  3. Hanami::Mailer.configure do
  4. # ...
  5. root 'path/to/templates'
  6. end.load!

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