Lesson 2 — Attributes, booleans and data attributes
Passing attributes to tags
Every tag method accepts a hash of attributes as its first argument:
|
|
Attribute names map directly to HTML attribute names. Use symbols or strings — both work, though symbols are conventional.
Class is a reserved word — what about class:?
class is a Ruby reserved word, but Phlex handles it cleanly: pass class: as a keyword argument and Phlex writes class="..." in the output.
|
|
Dynamic attributes
Attributes are just Ruby expressions, so they can be dynamic:
|
|
Output:
|
|
Boolean attributes
HTML has boolean attributes — disabled, checked, required, readonly, multiple — that are either present or absent. In Phlex, pass true to include them and false (or omit) to exclude them:
|
|
Output:
|
|
false means the attribute is not written at all — exactly the right HTML behaviour.
Data attributes
Pass data attributes as a nested hash under data::
|
|
Output:
|
|
Phlex automatically converts nested hash keys to kebab-case data attributes. Underscores become hyphens: dropdown_target: → data-dropdown-target. This is exactly the format Stimulus expects — no string wrangling required.
Aria attributes
The same pattern works for aria::
|
|
Combining multiple classes dynamically
A common pattern is building a class string from multiple sources — a base class, a variant, and a conditional modifier:
|
|
Output:
|
|
We’ll refine this pattern considerably in Module 7 when we introduce design tokens, but this is the foundation.
Exercise
Create 02_exercise.rb. Build an InputComponent that renders an <input> element accepting type:, name:, placeholder:, required:, and disabled: arguments. Add a data: hash that includes a controller key set to "input-validation".
For example, calling it like this:
ruby
|
|
Should produce:
html
|
|
Notice that required: true becomes required="required", disabled: false is omitted entirely from the output, and the data: { controller: "input-validation" } hash becomes data-controller="input-validation".
Test it with at least three different configurations — try a disabled text field, a required password field, and a plain text field with no required or disabled state — so you can see how the boolean attributes behave in each case.
Solution to Exercise 02
|
|