The context method returns a hash that’s shared across all components in the render tree:
class Navigation < Phlex::HTML def view_template nav do ul do li { a(href: "/") { "Home" } } li { a(href: "/about") { "About" } } if context[:show_about] li { a(href: "/admin") { "Admin" } } if context[:current_user]&.admin? end end endend
Context is scoped to the render tree - it’s available from when rendering starts until rendering completes:
class Component < Phlex::HTML def initialize # ❌ Can't access context here - not rendering yet # context[:value] # Raises Phlex::ArgumentError end def view_template # ✅ Can access context during rendering div { context[:value] } end def after_render # ✅ Can access context in lifecycle hooks log_render if context[:debug] endend
Accessing context before rendering starts will raise a Phlex::ArgumentError with the message: “You can’t access the context before the component has started rendering.”
Share request details throughout your component tree:
class Layout < Phlex::HTML def view_template nav do ul do menu_item("Home", "/") menu_item("About", "/about") menu_item("Contact", "/contact") end end end private def menu_item(label, path) current = context[:request_path] == path li(class: current ? "active" : nil) do a(href: path) { label } end endend# Render with request pathLayout.new.call(context: { request_path: request.path })
class ThemedButton < Phlex::HTML def initialize(text) @text = text end def view_template button(class: button_classes) { @text } end private def button_classes theme = context[:theme] || :light case theme when :dark "bg-gray-800 text-white" when :light "bg-white text-gray-800" end endend
class Parent < Phlex::HTML def initialize(user) @user = user end def view_template # Must explicitly pass user to child render Child.new(@user) endendclass Child < Phlex::HTML def initialize(user) @user = user end def view_template h1 { @user.name } endend
Use context for data that many components need (like current user, request info, or theme). Use instance variables for component-specific data.
Use the rendering? method to check if context is available:
class Component < Phlex::HTML def safe_context_access if rendering? context[:value] else nil end end def view_template div { safe_context_access } endend