A Rails template handler that lets you write Phlex components directly in .html.rb view files.
Run the following command from the root of your Rails project:
# Make sure you've installed phlex-rails
bundle add 'phlex-rails-template'Create view files with the .html.rb extension:
# app/views/posts/show.html.rb
h1 { @post.title }
div(class: "content") do
p { @post.body }
endIn your controller:
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
# Renders app/views/posts/show.html.rb automatically
end
endController instance variables are automatically available in your templates.
You can customize how components are instantiated and how variables are assigned by passing a block to register:
# config/initializers/phlex_rails_template.rb
Phlex::Rails::Template.register :rb do
# Override the base component class
def component_class
ApplicationComponent
end
# Override to instantiate the component with custom arguments
def create_component(component_class)
component_class.new(view_context.session, request: view_context.request)
end
# Override to customize how controller variables are assigned
def assign_variables
view_context.assigns.each do |key, value|
component.instance_variable_set(:"@#{key}", "PREFIX: #{value}")
end
end
endOr you can pass a configurator class directly:
class CustomConfigurator < Phlex::Rails::Template::Configurator
def component_class
ApplicationComponent
end
end
Phlex::Rails::Template.register :rb, CustomConfiguratorYou can also register additional template handlers with different configurators:
Phlex::Rails::Template.register :customrb, MyCustomConfiguratorThe gem is available as open source under the terms of the MIT License.