Phlex is Ruby
Phlex is just Ruby. The most basic Phlex component looks like this:
class MyComponent < Phlex::HTML
def initialize(name:)
@name = name
end
def view_template
h1(class: "text-2xl font-bold") { "Hello, #{@name}!" }
end
end
Then, to render the component, you can use the render method:
render MyComponent.new(name: "World")
Let’s take a closer look at how Phlex components work.
HTML tags are methods in Phlex
Phlex provides a set of methods for rendering HTML tags. These methods are named after the HTML tags they represent, and they take a block of code that will be executed to generate the content of the tag.
Consider the following HTML:
<h1 class="text-2xl font-bold">Hello, World!</h1>
Here’s how you’d render it in Phlex:
h1(class: "text-2xl font-bold") { "Hello, World!" }
The view_template method
When Phlex components are rendered, they call the view_template method. This method is where you implement the logic for rendering the component’s HTML.
Ruby in components
For example, if you want to add a helper method to adjust the greeting based on the time of day, you can do something like this:
class MyComponent < Phlex::HTML
def initialize(name:)
@name = name
end
def view_template
h1(class: "text-2xl font-bold") { greeting }
end
private
def greeting
case Time.now.hour
when 0..6
"Top of the morning to ya, #{@name}!"
when 7..11
"¡Buenos días, #{@name}!"
when 12..17
"Good afternoon, #{@name}!"
else
"¡Buenas noches, #{@name}!"
end
end
end
Rendering data
Rendering data from ActiveRecord models is just as intuitive as rendering data from any other Ruby object. For example, you could render a list of a users emails with a component like this.
class UserItemsList < Phlex::HTML
def initialize(user:)
@user = user
end
def view_template
h2(class: "text-lg font-semibold") { "Email List" }
ul do
@user.items.each do |item|
li { item.name }
end
end
end
end