In Phlex 2 with phlex-rails, how does a Phlex::HTML component produce markup, and how does it call Rails helpers such as link_to?
answer
- markup written as Ruby method calls
- view_template, not template
- escaped by default; raw needs safe
- helpers come in as adapter modules
- output helpers versus value helpers
basics
~20 sA Phlex component is a Ruby class inheriting from Phlex::HTML whose view_template method calls element methods such as div and p with blocks; output is escaped by default. Rails helpers are included as phlex-rails adapters, e.g. include Phlex::Rails::Helpers::LinkTo.
solid answer
~50 sIn Phlex 2 a component subclasses `Phlex::HTML` (in Rails, the `Components::Base` that `rails g phlex:install` creates) and defines `view_template`; inside it every HTML element is a method, `div(class: "alert") { p { @message } }`, and text is HTML-escaped. Phlex 1's `template` method was renamed: in Phlex 2 `template` is the `<template>` element, so a class that only defines `template` renders a "Phlex Warning" text instead of its markup. `raw` accepts only safe objects, so `raw(safe(html))`, or an `html_safe` string under phlex-rails; a plain string raises. Rails helpers are not methods on the component: you include adapter modules such as `Phlex::Rails::Helpers::LinkTo` or `NumberToCurrency`, and register your own with `register_output_helper` (writes to the buffer) or `register_value_helper` (returns a value you output with `plain`). The old `helpers` proxy is deprecated in phlex-rails 2.4. Rails renders it like any component: `render Components::Alert.new(kind: :warning, message: "...")`.
code
ruby · 16 lines# app/components/claim_total.rb
class Components::ClaimTotal < Components::Base
include Phlex::Rails::Helpers::NumberToCurrency
def initialize(claim:)
@claim = claim
end
def view_template
p(class: "claim-total") do
plain "Total claimed: "
# a value helper must be output explicitly
plain number_to_currency(@claim.amount)
end
end
endgo deeper
Recognise a Phlex component: a Ruby class with view_template and element methods, rendered with render Component.new.
Explain escaping and raw with safe, the Phlex 2 rename, and output versus value helper adapters, including register_output_helper.
Judge whether Ruby-only markup suits the team, plan a Phlex 1 to 2 upgrade, and set up a base class with the shared helper adapters.
Weigh Phlex against ViewComponent or ERB partials for a codebase: who edits markup, how helpers are reached, and the cost of a third view style.
## Markup as Ruby **Phlex** builds HTML from plain Ruby objects: no template file, no ERB. Each HTML element is a method on `Phlex::HTML`, attributes are keyword arguments, and nesting is done with blocks. In a Rails app the **phlex-rails** gem connects it to Action View, and its installer sets up the folders: ```bash bin/rails generate phlex:install bin/rails generate phlex:component Alert ``` `phlex:install` creates `Components::Base < Phlex::HTML` (which includes `Phlex::Rails::Helpers::Routes`, so path helpers work) and `Views::Base`, and registers `app/components` and `app/views` with Zeitwerk under the `Components` and `Views` namespaces. The component generator writes `app/components/alert.rb`. ## A component for the claims portal ```ruby class Components::Alert < Components::Base include Phlex::Rails::Helpers::LinkTo def initialize(kind:, message:, claim: nil) @kind, @message, @claim = kind, message, claim end def view_template div(class: ["alert", "alert--#{@kind}"], role: "alert") do p { @message } link_to("Open claim", claim_path(@claim)) if @claim end end end ``` How the output is built: - **`view_template`** is the entry point; Phlex calls it when rendering. - An element's **block** can write children; if it writes nothing, its **return value** is output, so `p { @message }` prints the message. - Text is **HTML-escaped** whether it comes from a block's return value or `plain`, and attribute values have their quotes escaped, so user input cannot break out of an attribute. - **`raw`** writes unescaped output but only accepts safe objects: `raw(safe("<b>approved</b>"))`. With phlex-rails, `ActiveSupport::SafeBuffer` counts as safe, so an `html_safe` string works; a plain `String` raises `Phlex::ArgumentError`. - Rendering the same instance twice raises **`Phlex::DoubleRenderError`**. ## Phlex 2 renamed the entry point In Phlex 1 the method was `template`. Phlex 2 renamed it to **`view_template`** and turned `template` into the method for the HTML `<template>` element. An upgraded class that still defines only `template` does not raise: the base `view_template` prints a "Phlex Warning" telling you to rename it. A view that shows that text instead of the alert is the symptom. ## Calling Rails helpers A Phlex component is not an Action View template, so `link_to` and `number_to_currency` are not methods on it. phlex-rails provides **adapter modules**, one per helper, under `Phlex::Rails::Helpers`: | Kind | Example adapter | Behaviour inside `view_template` | |---|---|---| | output helper | `LinkTo`, `ButtonTo`, `FormWith` | writes the helper's HTML straight into the output | | value helper | `NumberToCurrency`, `DOMID` (for `dom_id`) | returns a value; you output it with `plain` or use it as an attribute | The distinction matters. `link_to(...)` alone emits a link. `number_to_currency(@claim.amount)` alone emits nothing if anything else was already written in that block; write `plain number_to_currency(@claim.amount)`. For your own helpers from `app/helpers`, register adapters on the component class: - `register_output_helper :claim_status_badge` for helpers that return HTML to insert; - `register_value_helper :claim_reference` for helpers that return data; - `register_builder_yielding_helper` for helpers that yield a form-builder-like object. If a component calls a built-in Rails helper it has not included, phlex-rails raises `NoMethodError` with a hint naming the adapter module to include. The catch-all `helpers` proxy still exists in phlex-rails 2.4 but prints a deprecation warning; `view_context` is the explicit escape hatch and raises before rendering starts. ## Rendering from Rails Phlex components respond to `render_in`, so Rails renders them anywhere it renders objects: 1. from ERB: `<%= render Components::Alert.new(kind: :warning, message: "Upload the police report") %>`; 2. from a controller: `render Views::Claims::Show.new(claim: @claim)` for a full page; 3. inside another Phlex component: `render Components::Alert.new(...)`. Path helpers such as `claim_path` come from `Phlex::Rails::Helpers::Routes`, which the generated `Components::Base` already includes. ## Mistakes interviewers listen for | Belief | What Phlex actually does | |---|---| | the entry point is `template` | Phlex 2 calls `view_template`; `template` is the `<template>` element | | `raw("<b>x</b>")` trusts a string | `raw` refuses unsafe objects; wrap with `safe` | | every Rails helper just works | include an adapter or register one | | `number_to_currency(...)` prints itself | value helpers return; output them with `plain` | | a Phlex component needs a template file | markup is the Ruby in `view_template` | Interviewers rarely expect Phlex in depth; knowing the entry point, the escaping rule and the adapter model shows you have used it rather than read its README.
- Why does a Phlex 1 component show a 'Phlex Warning' text after upgrading to Phlex 2?Phlex 2 calls `view_template`, and the class only defines the old `template` method, which now overrides the `<template>` element method instead. The inherited `view_template` prints a warning asking you to rename the method. Renaming `template` to `view_template` fixes it.
- How do you make an app helper such as claim_status_badge callable in Phlex components?Register an adapter on a base class: `register_output_helper :claim_status_badge` if it returns HTML to insert, or `register_value_helper` if it returns data you will print with `plain` or pass as an attribute. The adapter forwards the call to the Rails view context during rendering.
- Phlex 2 components define a template method as their entry point
- raw("<b>text</b>") outputs a plain string unescaped in Phlex
- Every Rails helper is callable in a Phlex component without includes
- number_to_currency writes its result into the Phlex output by itself
- Phlex components need a sidecar .html.erb template
Assumes Phlex 2.4 with phlex-rails 2.4 on Rails 8.1: view_template replaced Phlex 1's template, and the helpers proxy is deprecated in phlex-rails 2.4.