Viewing the Data

Since ours is a very simple blog app, we’ll only use the view and template bits for now.

Let’s start by passing the data from the relevant action into a “view”. For the blog index view, create an index.rb file under .../slices/main/lib/main/views/blog/

# frozen_string_literal: true

#.../slices/main/lib/main/views/blog/index.rb

module Main
  module Views
    module Blog
      class Index < View::Base
        expose :blogs
      end
    end
  end
end

Here, we are telling the view that data will be passed into it via the blogs variable from the related action.

Now all that’s left for us to be able to view the blogs data on the web browser is to create a template view to render the data.

h1 A listing of all blogs

ul
  - blogs.each do |blog|
    li: a href="/blogs/#{blog.id}" = blog.title

Templates can be in erb, haml, or slim. What’s available by default from the Hanami 2 template project is slim.

In the template, we are doing a simple iteration on the blogs variable to give us a list of blog titles that should now be viewable on the browser.

script/server

Assuming nothing breaks, head over to localhost:3000/blogs and view your list of blog posts.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *