An object oriented view layer for Hanami. Write views, layouts and components as Phlex classes instead of templates.
Add the gem to your Gemfile:
gem "phlex-hanami", "~> 0.2.0"Or, from gem.coop:
gem "phlex-hanami", "~> 0.2.0", source: "https://gem.coop/@aaron"Note
@stephannv wrote this gem and @aaronmallen now maintains it. 0.1.0 on RubyGems is theirs and shares no code with what is here. Releases from 0.2.0 on come from this repository.
Give the app a base view:
# app/view.rb
module MyApp
class View < Phlex::Hanami::View
end
endExpose what the view needs from the action:
# app/actions/posts/index.rb
module MyApp
module Actions
module Posts
class Index < MyApp::Action
include Deps["posts_repo"]
def handle(_request, response)
response[:posts] = posts_repo.all
end
end
end
end
endWrite the view under the Views namespace, with the matching name:
# app/views/posts/index.rb
module MyApp
module Views
module Posts
class Index < MyApp::View
def initialize(posts:) = @posts = posts
def view_template
h1 { "Posts" }
ul do
@posts.each { |post| li { a(href: path(:post, id: post.id)) { post.title } } }
end
end
end
end
end
endThat is the whole setup. Hanami pairs the action with the view whose name matches and renders it. You write no
response.render call and change no configuration.
Name a layout Views::Layout and every view in the slice renders inside it:
# app/views/layout.rb
module MyApp
module Views
class Layout < Phlex::Hanami::Layout
def view_template
doctype
html do
head do
title { content_for(:page_title) || "MyApp" }
link(rel: "stylesheet", href: asset_url("app.css"))
end
body { yield }
end
end
end
end
end- Views: base classes, how a view is paired with an action, and what it receives
- Layouts: the slice convention, per view overrides and opting out
- Components: the component base class, kits, and sharing components between slices
- View context: routes, assets,
content_for, flash, session and request - Helpers: Hanami's helper library, escaping and translations
- Responses: content types, JSON actions,
HEADrequests and opting out of auto render - Mailers: Phlex views for hanami-mailer, and the plain text part
- Testing: helpers for view and component specs, under RSpec or Minitest
- How it works: what the gem installs, and why each piece is there
-
hanami generateproducing Phlex views instead of ERB templates
This project uses mise for tools and tasks. Run mise tasks to see them all.
mise run setup # Install tools and dependencies
mise run test # Run the test suite, with the RBS signatures checked as it goes
mise run format # Format every file
mise run lint # Lint every fileCONTRIBUTING covers the rest, including how the signatures are generated.
This project is licensed under the MIT License