You can create an HTML view by subclassing
Phlex::HTML and defining a
template instance method.
template method determines what your view will output when its rendered. The above example calls the
h1 method which outputs an
<h1> tag. Switch to the “Output” tab above to see for yourself.
You can define an initializer for your views just like any other Ruby class. Let’s make our
Hello view take a
name as a keyword argument, save it in an instance variable and render that variable in the template.
We’ll render this view with the arguments
name: "Joel" and see what it produces.
Views can render other views in their templates using the
render method. Let's try rendering a couple of instances of this
Hello view from a new
Example view and look at the output of the
Views can also yield content blocks, which can be passed in when rendering. Let's make a
Card component that yields content in an
<article> element with a
drop-shadow class on it.
Example view renders a
Card and passes it a block with an
Looking at the output of the
Example view, we can see the
<h1> element was rendered inside the
<article> element from the
Since the block of content was the only thing we need in the
<article> element, we could have just passed the content block directly to the element instead.
class Card < Phlex::HTML def template(&) article(class: "drop-shadow", &) end end
You can hook into the rendering process by overriding
after_template which are called immediately before / after the template is rendered.
It’s a good idea to call
super to allow for inherited callbacks.