Lesson 6 — Building HTML strings without a component class
When you don’t need a class
Sometimes you just want to build a small HTML fragment without the overhead of defining a full component class. Phlex provides two ways to do this.
Phlex::HTML.new with a block (inline rendering)
You can instantiate Phlex::HTML directly and pass a block:
|
|
Output:
|
|
Useful for one-off fragments in scripts, tests, or generators.
The Phlex.fragment helper
For even smaller inline fragments, Phlex.fragment produces an HTML string directly:
|
|
Practical use: generating HTML in a script
The real value of standalone Phlex without Rails is in scripts, data exporters, email generators, and test helpers. Here’s a realistic example — a script that generates an HTML report from a data structure:
|
|
Run it:
|
|
Open report.html in a browser. It’s a fully rendered HTML document.
doctype
Notice that the example above calls html do ... end, which produces <html>...</html>. To get a proper <!DOCTYPE html> declaration, use the doctype method:
|
|
Using Phlex::HTML in a Rack app (preview of what Rails does)
Just to make the bridge to Rails concrete, here’s a Phlex component serving HTTP responses through a bare Rack app:
|
|
This is almost exactly what Rails does under the hood: a controller calls a view object’s render method and returns the HTML string as the response body. Rails adds routing, middleware, and convention — but the Phlex rendering mechanism is identical to this.
Exercise
Create 06_exercise.rb. Write a script that generates a standalone HTML page containing a table of five fictional products — name, price, and stock count. Use at least two component classes (ProductTable and a ProductRow sub-component). Call doctype and wrap everything in an html/head/body structure. Write the output to products.html and open it in a browser.
Solution to Exercise 06
|
|
Module 2 summary
You now have a complete mental model of Phlex without any Rails magic obscuring it:
- A Phlex component is a Ruby class with a
view_templatemethod - HTML tags are Ruby method calls; nesting is done with blocks
- Data comes in through
initialize— the interface is always explicit - Attributes are keyword arguments; booleans,
data:, andaria:all follow natural Ruby patterns - Text content is always escaped — XSS is structurally prevented, not bolted on
- Raw HTML requires an explicit
safe()declaration — no accidental bypasses - SVG components inherit from
Phlex::SVGand work identically to HTML components - You can generate HTML strings without a component class using
Phlex.fragmentor inline blocks - A Phlex component is just an object that returns an HTML string from
call— Rails uses this, but it doesn’t require Rails
In Module 3 we take these primitives and start building real component architecture: base classes, composition, kits, and the first components of Phlex::UI.