Lesson 1 — Your first component: view_template, tags, nesting
What is a Phlex component?
A Phlex component is a Ruby class that inherits from Phlex::HTML and defines a method called view_template. That method describes the HTML structure using Ruby method calls.
Every HTML tag has a corresponding Ruby method. You nest elements by passing blocks. That’s the entire mental model.
Hello, Phlex
Create 01_hello.rb:
|
|
Run it:
|
|
One method call. One HTML element. The block’s return value becomes the element’s text content.
Nesting elements
HTML is a tree. Phlex mirrors that with nested blocks:
|
|
Output (formatted for readability):
|
|
The indentation in the Ruby mirrors the HTML structure exactly. This is one of Phlex’s great readability wins over ERB — the nesting is visible in the code, not implied by open/close tags.
Accepting data via initialize
A component that only renders static content isn’t very useful. Components accept data through their initializer:
|
|
Output:
|
|
Notice the explicit interface: keyword arguments, defaults, no surprises. Anyone reading UserCard.new(...) knows exactly what data the component needs. This is the first big advantage over ERB partials, which accept locals implicitly.
Ruby logic inside view_template
Because view_template is just a Ruby method, you can use any Ruby you like:
|
|
Output:
|
|
each, map, if, case, unless — all of it works, because it’s all just Ruby.
Rendering one component inside another
Components compose naturally:
|
|
Output:
|
|
render is how you embed one component inside another. The rendered component’s output is inserted at that point in the parent’s HTML tree.
Exercise
Create 01_exercise.rb. Build a NavigationComponent that renders a <nav> containing a <ul> with three <li> items: Home, About, Contact. Each <li> should contain an <a> tag. Pass the nav items in as an array of hashes [{ label:, href: }] via initialize.
Note: An
<a>tag with anhrefattribute looks like this:a(href: "/") { "Home" }— we’ll cover attributes properly in Lesson 2.
Calling it like:
|
|
should produce:
|
|
Solution to Exercise 01
|
|