phlex
phlex copied to clipboard
Support Rails rendering
WIP combining the work from #69 and #68.
I’ve also added the ability to capture ERB yielded into a Phlex component.
Initial Rails Support
Just update your Gemfile
to require phlex/rails
.
gem "phlex", require: "phlex/rails"
Rendering a Rails partial in a component
You can now render a Rails partial inside a component.
class ExampleComponent < Phlex::Component
def initialize(articles:)
super
end
def template
ul do
@articles.each do |article|
li do
render @article # renders the partial views/articles/_article.html.erb
end
end
end
end
end
Rendering a Phlex Component from a Rails ERB view
You can also render a Phlex component from an ERB view and even pass ERB content into it.
<%= render CardComponent.new do %>
<h1>Hello world!</h1>
<% end %>
Here the block is passed to the render
helper method rather than the new
method on CardComponent
. You can write your component content in Phlex instead by passing the block to the new
method. The easiest way to do this is to use a brace block.
<%= render CardComponent.new {
h1 "Hello world!"
} %>
@joeldrapper I've gotten a variation of this working in Bridgetown as well!
Repo: https://github.com/jaredcwhite/test-bt-and-phlex (component here, ERB template, page with "inline phlex") Demo: https://test-bt-and-phlex.onrender.com/
The rendering support is added here much like your Rails context mixin. I wonder if there's a way to DRY this up between the two.
I also experimented with an "inline phlex" helper which basically creates a component on the fly. Pretty neat-o in a page template. Probably not great in high-performance scenarios, but on a small static site it's definitely acceptable: https://github.com/jaredcwhite/test-bt-and-phlex/blob/main/plugins/builders/inline_phlex.rb