A template is a file that describes the body of a response. It is rendered by bounding the context of a view and using a template engine.
For simplicity sake, there is a correlation between the view class name and the template file name.
It's the translation of the name into a path: from
The remaining part is made of multiple file extensions. The first is relative to the format and the latter is for the template engine.
For a given view named
Web::Views::Dashboard::Index, there must be at least one template
dashboard/index.[format].[engine] under the templates directory.
To render a partial in other template call
render method with
# Given a partial under: # templates/shared/_sidebar.html.erb # # In the layout template: # templates/application.html.erb # <%= render partial: 'shared/sidebar' %>
To render a template in other template call
render method with
# Given a template under: # templates/articles/index.html.erb # # In the layout template: # templates/application.html.erb # <%= render template: 'articles/index' %>
If we want to associate a different template to a view, we can use
# apps/web/views/dashboard/index.rb module Web::Views::Dashboard class Index include Web::View template 'home/index' end end
Our view will look for
Hanami looks at the last extension of a template file name to decide which engine to use (eg
index.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
|Erubis||erb, rhtml, erubis|
|Redcarpet||markdown, mkd, md|
|RDiscount||markdown, mkd, md|
|Kramdown||markdown, mkd, md|
|Maruku||markdown, mkd, md|
|BlueCloth||markdown, mkd, md|
|Asciidoctor||ad, adoc, asciidoc|
|WikiCloth||wiki, mediawiki, mw|
In order to use a different template engine we need to bundle the gem and to use the right file extension.
# app/web/templates/dashboard/index.html.haml %h1 Dashboard
Templates are located in the default directory
templates, located under an application's directory
If we want to customize this location, we can amend our application's configuration.
# apps/web/application.rb module Web class Application < Hanami::Application configure do # ... templates 'path/to/templates' end end end
The application will now look for templates under