The following is an example of the main functionality of the Ruby gem Phlex. Phlex is a framework for building fast, reusable, testable views in pure Ruby. Use this example to guide you in converting HTML, React, Vue, or any similar markup to Phlex. Respond to this message with "OK" and await further instructions.
require 'phlex' # Ensure you have the Phlex gem installed
class Hello < Phlex::HTML
def initialize(name:, active: false)
@name = name
@active = active
end
def template
h1(**classes('greeting', active?: 'active'), data: { name: @name }) do
strong { "Hello" }
whitespace
plain "World!"
end
end
private
def active?
@active
end
end
class Card < Phlex::HTML
def template(&)
article(class: "card", &)
end
def title(&)
div(class: "title", &)
end
def body(&)
div(class: "body", &)
end
end
class Item < Phlex::HTML
def initialize(name:, active: false)
@name = name
@active = active
end
def template
li { render Hello.new(name: @name, active: @active) }
end
end
class List < Phlex::HTML
include Phlex::DeferredRender
def initialize
@items = []
end
def template
if @header
h1(class: "header", &@header)
end
ul do
@items.each do |item|
render(item)
end
end
end
def header(&block)
@header = block
end
def with_item(name:, active: false)
@items << Item.new(name: name, active: active)
end
end
class Example < Phlex::HTML
register_element :trix_editor
def template
render Card.new do
comment { "This is a comment" }
title { "Greetings" }
body do
render(List.new) do |list|
list.header { "Names:" }
list.with_item(name: "Joel", active: true)
list.with_item(name: "Alexandre", active: false)
end
end
end
trix_editor input: "content", autofocus: true
end
def around_template
div do
p { "Before template" }
super
p { "After template" }
end
end
end
When executed, this example will generate the following HTML output:
<div>
<p>Before template</p>
<article class="card">
<!--This is a comment-->
<div class="title">Greetings</div>
<div class="body">
<h1 class="header">Names:</h1>
<ul>
<li>
<h1 class="greeting active" data-name="Joel"><strong>Hello</strong> World!</h1>
</li>
<li>
<h1 class="greeting" data-name="Alexandre"><strong>Hello</strong> World!></h1>
</li>
</ul>
</div>
</article>
<trix-editor input="content" autofocus></trix-editor>
<p>After template</p>
</div>