Lesson 5 — SVG components
Why SVG in Phlex?
Icons are everywhere in modern UIs, and inline SVG is often the best approach: perfectly sharp at any size, styleable with CSS, no extra HTTP request, and accessible with aria attributes. ERB makes inline SVG painful — you end up with raw XML pasted into your templates. Phlex makes SVG a first-class citizen.
Phlex::SVG vs Phlex::HTML
For SVG content, inherit from Phlex::SVG instead of Phlex::HTML. This gives you all the SVG element methods (path, circle, rect, line, polyline, polygon, g, defs, use, etc.):
|
|
Notice stroke_linecap: — underscores in attribute names are converted to hyphens, matching SVG conventions.
Embedding SVG inside HTML components
A Phlex::SVG component can be rendered inside a Phlex::HTML component just like any other component:
|
|
A reusable icon system
In practice, you’ll want a family of icons with a consistent interface. Here’s a pattern that works well:
|
|
This pattern — a base class with a icon_paths hook — gives every icon a consistent size API, accessibility attributes, and class support, while keeping each icon file to just the path and shape definitions.
Exercise
Add a ChevronIcon to the icon family from the lesson. The SVG path is a single polyline:
|
|
Add it to the NavBar component alongside the existing HomeIcon, UserIcon, and SettingsIcon. Then redirect the output to an HTML file and open it in a browser:
|
|
You should see:
Solution to Exercise 05
Add this class after the SettingsIcon class, and add a render line in the view_template.
|
|