From Rails to Hanami: Views


This is the third and last part of the “From Rails to Hanami” series and now we’re back to talk about Views. You can also check out the other parts about Models and Controllers.
If you are used to Rails, you may be thinking: what to say about Views? Isn’t it just the HTML files? And that’s where you are wrong! In Hanami, these files are called templates.
Templates
Templates are what you expect from a normal Rails view: an HTML ERB file with the contents to be rendered.
Taking off from our Controllers overview, the template for our “tasks index” action will live under apps/web/templates/tasks/index.html.erb, and its first version will look like this:
You are probably thinking: “Where did that title come from?", and that question leads us to Hanami views.
Views
Views are objects responsible for rendering a template and handing data for it to consume. The naming convention for a view class follows the same pattern as that of action classes, which have been mentioned in our last post. Hence, for a Web::Controller::Tasks::Index action we need a Web::Views::Tasks::Index view. That convention is very important because that's how the framework knows which view object to run after the action has finished its job.
To make the template above work, our view would have to look like this:
You may be wondering, where does tasks come from? Do you recall the exposure feature that we talked about in the last post? Exposure is the Hanami way to pass data to the views — in other words, the variables that we expose on the actions are made available within the views!
And it is easy to add elements to your template and to your view. Let’s say we want a list of tasks; in that case, our template will look like this:
And our view object will have the necessary logic behind it:
Presenters are objects that wrap another object (such as Task) and augment it with logic responsible for representing it in a given context, in our case: display a task as a list item. Notice how we are retrieving a list of tasks in our view and wrapping each one in a presenter.
The raw method over there is the way to mark an output as “html safe”, as known in Rails.
This way you will have a way cleaner ERB template, just the way it has to be: representation of data without any actual logic — because your frontend should not know about how data is put together.
As a good side effect, our views get very easy to unit test. At first, it may look overly complicated, but I can ensure you that it is not! And with practice you’ll get more productive!
Wrap up
And we reached the end of this series — for now. If you want to know more about Hanami, I encourage you to check out the project’s official site, especially the Hanami guides. For more details about views, you can visit this link.
If you enjoyed this article, recommend it and follow me. If you have any questions regarding the topic, do not hesitate to leave a comment.