Use case #12: Easily customizing page parameters
My initial reflex while trying to set dynamic / nav parameters of the page (like a title, breadcrumbs..) was to use layout-level exposures in the views: expose :title, :layout => true
While technically possible, I found it a bit tedious to do, because in fact it made more sense to live inside the template itself, which receives all the useful information ready to use.
This is possible very easily thanks to the context method content_for
Views / Context · Hanami v2.3 · Hanakai
That way, you can set a dynamic information from any template:
<!-- templates/catalog/configuration.html.erb -->
<% content_for :title, "Configure catalog #{catalog.name}" %>
<div>
<h1>Catalog configuration / <%= catalog.name %></h1>
</div>
And then use it from the layout, or any other template:
<!-- templates/layout/app.html.erb -->
<html>
<head>
<title><%= content_for :title %></title>
</head>
<body>
<%= yield %>
</body>
</html>
In my example, this will render:
<html>
<head>
<title>Configure catalog Foo</title>
</head>
<body>
<div>
<h1>Catalog configuration / Foo</h1>
</div>
</body>
</html>
Very simple, very powerful. I wished I’d knew it earlier ![]()
Happy coding ! ![]()
![]()