Phlex is Ruby
Phlex is just Ruby. The most basic Phlex component looks like this:
class MyComponent < Phlex::Component
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:
π Unlock content
Pre-order this course to unlock this video, source code, and content.
ββ(class: "text-2xl font-bold") { "Hello, World!" }
The view_template
method
ββββ βββββ ββββββββββ βββ βββββββββ ββββ ββββ βββ βββββββββββββ βββββββ ββββ ββββββ ββ βββββ βββ βββββββββ βββ βββββ βββ βββββββββ βββ βββββββββββ βββββ
Ruby in components
βββ ββββββββ ββ βββ ββββ ββ βββ β ββββββ ββββββ ββ ββββββ βββ ββββββββ βββββ ββ βββ ββββ ββ ββββ βββ βββ ββ βββββββββ ββββ βββββ
class MyComponent < βββββ::βββββββββ
def ββββββββββ(name:)
βββββ = name
end
def βββββββββββββ
ββ(class: "text-2xl font-bold") { ββββββββ }
end
private
def ββββββββ
case ββββ.βββ.ββββ
when 0..6
"Top of the morning to ya, #{βββββ}!"
when 7..11
"Β‘Buenos dΓas, #{βββββ}!"
when 12..17
"Good afternoon, #{βββββ}!"
else
"Β‘Buenas noches, #{βββββ}!"
end
end
end
Rendering data
βββββββββ ββββ ββββ ββββββββββββ ββββββ ββ ββββ ββ βββββββββ ββ βββββββββ ββββ ββββ βββ βββββ ββββ βββββββ βββ ββββββββ βββ βββββ ββββββ β ββββ ββ β βββββ ββββββ ββββ β βββββββββ ββββ βββββ
class UserEmailList < βββββ::βββββββββ
def ββββββββββ(ββββ:)
βββββ = ββββ
end
def βββββββββββββ
ββ(class: "text-lg font-semibold") { "Email List" }
ββ do
βββββ.ββββββ.ββββ do |βββββ|
ββ { ββββββ βββββ.βββββββ }
end
end
end
private
def ββββββ(βββββββ, **)
β(href: "mailto:#{βββββββ}", **) {
block_given? ? yield : βββββββ
}
end
end