### Usage of Select
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Example of using `select` to create a dropdown with basic options.
```ruby
form.select :category, ["Option 1", "Option 2"]
```
--------------------------------
### Helper Composition Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
An example demonstrating how to compose multiple Phlex Rails helpers within a component.
```APIDOC
## Helper Composition Example
This example shows how to include and use `LinkTo`, `CurrentPage`, and `ImageTag` helpers together in a `Phlex::HTML` component.
```ruby
class NavigationBar < Phlex::HTML
include Phlex::Rails::Helpers::LinkTo
include Phlex::Rails::Helpers::CurrentPage
include Phlex::Rails::Helpers::ImageTag
def view_template
nav(class: "navbar") do
link_to(image_tag("logo.svg"), root_path, class: "navbar-brand")
ul(class: "nav-links") do
li { nav_link("Home", root_path) }
li { nav_link("Blog", posts_path) }
li { nav_link("Contact", contact_path) }
end
end
end
private
def nav_link(text, path)
active = current_page?(path)
link_to(text, path, class: ["nav-link", ("active" if active)])
end
end
```
```
--------------------------------
### ButtonTag Usage Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Example of how to use the `button_tag` helper to create a button with specified text, type, and CSS classes.
```ruby
button_tag "Click Me", type: "submit", class: "btn"
```
--------------------------------
### Install Gem
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/configuration.md
Run bundle install after adding the gem to your Gemfile to install the Phlex Rails integration.
```bash
bundle install
```
--------------------------------
### Example: Get Layout Identifier
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
Shows how to instantiate a layout and retrieve its identifier. The identifier corresponds to the class name of the layout.
```ruby
layout = ApplicationLayout.new
layout.identifier # => "ApplicationLayout"
```
--------------------------------
### Virtual Path Calculation Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
Demonstrates how the `virtual_path` is calculated for different layout class names, including nested namespaces.
```ruby
class ApplicationLayout < Phlex::HTML
include Phlex::Rails::Layout
end
ApplicationLayout.virtual_path # => "application_layout"
class Admin::DashboardLayout < Phlex::HTML
include Phlex::Rails::Layout
end
Admin::DashboardLayout.virtual_path # => "admin.dashboard_layout"
```
--------------------------------
### Rails Controller Integration Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
Example of how a Rails controller uses a Phlex layout. The `ApplicationLayout.render` method is invoked internally by Rails during the rendering process.
```ruby
# In Rails controller
class PostsController < ApplicationController
layout "application" # Uses ApplicationLayout
def index
@posts = Post.all
render template: "posts/index"
end
end
# The ApplicationLayout.render is called by Rails with:
# - view_context: the controller's view context
# - block: content from posts/index template
```
--------------------------------
### Example: Get Layout Virtual Path
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
Demonstrates obtaining the virtual path of a layout instance. The virtual path is derived from the class name and formatted for Rails.
```ruby
layout = ApplicationLayout.new
layout.virtual_path # => "application_layout"
```
--------------------------------
### SubmitTag Usage Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Example of how to use the `submit_tag` helper to create a form submission button with custom text and CSS classes.
```ruby
form.submit "Save Changes", class: "btn btn-primary"
```
--------------------------------
### Complete Form Example with Phlex Rails Helpers
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
An example demonstrating how to build a complete article edit form using various Phlex Rails form helpers, including `form_with`, `text_field`, `collection_select`, `text_area`, `label`, and `submit_tag`.
```ruby
class ArticleEditForm < Phlex::HTML
include Phlex::Rails::Helpers::FormWith
include Phlex::Rails::Helpers::TextField
include Phlex::Rails::Helpers::TextArea
include Phlex::Rails::Helpers::SubmitTag
include Phlex::Rails::Helpers::Label
include Phlex::Rails::Helpers::CollectionSelect
include Phlex::Rails::Helpers::ContentTag
def initialize(article)
@article = article
end
def view_template
form_with(model: @article, local: true) do |form|
div(class: "form-group") do
form.label :title
form.text_field :title, class: "form-control"
end
div(class: "form-group") do
form.label :category_id
form.collection_select(
:category_id,
Category.all,
:id,
:name,
class: "form-control"
)
end
div(class: "form-group") do
form.label :content
form.text_area :content, class: "form-control", rows: 10
end
form.submit "Save Article", class: "btn btn-primary"
end
end
end
```
--------------------------------
### Helper Composition Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
Demonstrates composing multiple Phlex::Rails helpers within a Phlex component to build complex UI elements like navigation bars.
```ruby
class NavigationBar < Phlex::HTML
include Phlex::Rails::Helpers::LinkTo
include Phlex::Rails::Helpers::CurrentPage
include Phlex::Rails::Helpers::ImageTag
def view_template
nav(class: "navbar") do
link_to(image_tag("logo.svg"), root_path, class: "navbar-brand")
ul(class: "nav-links") do
li { nav_link("Home", root_path) }
li { nav_link("Blog", posts_path) }
li { nav_link("Contact", contact_path) }
end
end
end
private
def nav_link(text, path)
active = current_page?(path)
link_to(text, path, class: ["nav-link", ("active" if active)])
end
end
```
--------------------------------
### Example: Application Layout with Phlex::Rails::Layout
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
Demonstrates how to define an application layout using Phlex::Rails::Layout, including navigation and rendering content from the view context. Ensure `Phlex::Rails::Layout` is included in your layout class.
```ruby
class ApplicationLayout < Phlex::HTML
include Phlex::Rails::Layout
def view_template
html do
body do
nav { "Navigation" }
main do
# Renders content from the view
render(:content)
end
end
end
end
end
```
--------------------------------
### LinkTo Usage Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
Demonstrates how to use the `link_to` helper within a Phlex component to create navigation links. Supports standard link arguments like `class` and `id`.
```ruby
class Navigation < Phlex::HTML
include Phlex::Rails::Helpers::LinkTo
def view_template
nav do
link_to("Home", "/")
link_to("About", about_path)
link_to("Contact", contact_path, class: "nav-link")
end
end
end
```
--------------------------------
### Example Usage of Fields Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Demonstrates how to use the `fields` helper to create a nested form structure for associated models.
```ruby
form.fields :comments do |comment_form|
comment_form.text_area :body
end
```
--------------------------------
### TextField Usage Examples
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Shows how to use `text_field` with a form builder and `text_field_tag` as a standalone helper for creating text input fields.
```ruby
# With form builder
form.text_field :name, class: "input"
# Standalone
text_field_tag :query, "", placeholder: "Search"
```
--------------------------------
### Simple View with Rails Helpers
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/sgml.md
Example of a Phlex component using Rails helpers like ImageTag and LinkTo. Ensure the necessary helper modules are included.
```ruby
class UserProfile < Phlex::HTML
include Phlex::Rails::Helpers::ImageTag
include Phlex::Rails::Helpers::LinkTo
def initialize(user)
@user = user
end
def view_template
div(class: "profile") do
image_tag(@user.avatar, class: "avatar")
h1 { @user.name }
link_to "Edit", "/users/#{@user.id}/edit"
end
end
end
```
--------------------------------
### Conditional Link Helpers Usage Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
Shows how to use `link_to_if`, `link_to_unless`, and `link_to_unless_current` for dynamic link rendering based on conditions. These helpers are useful for creating navigation that adapts to user state or current page.
```ruby
include Phlex::Rails::Helpers::LinkToIf
include Phlex::Rails::Helpers::LinkToUnless
include Phlex::Rails::Helpers::LinkToUnlessCurrent
def view_template
# Only render link if user is signed in
link_to_if(user_signed_in?, "Profile", user_path(@user))
# Render link unless already on current page
link_to_unless_current("Home", root_path)
# Render "Active" text unless on admin page
link_to_unless(admin?, "Go Admin", admin_path)
end
```
--------------------------------
### Usage of FaviconLinkTag Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
Provides an example of using favicon_link_tag, commonly placed in layout templates.
```ruby
include Phlex::Rails::Helpers::FaviconLinkTag
def view_template
# Typically used in layouts
favicon_link_tag("icon.ico")
end
```
--------------------------------
### FormWith Usage Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Demonstrates how to use the `form_with` helper within a Phlex component to create a user form with label and text field.
```ruby
class UserForm < Phlex::HTML
include Phlex::Rails::Helpers::FormWith
def view_template
form_with(model: @user) do |form|
div do
form.label :name
form.text_field :name
end
end
end
end
```
--------------------------------
### Label Usage Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Demonstrates using the `label` helper with a form builder to associate a label with an email field.
```ruby
include Phlex::Rails::Helpers::Label
def view_template
form.label :email, "Email Address"
form.email_field :email
end
```
--------------------------------
### Usage of Collection Select
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Example of using `collection_select` to create a dropdown from a collection of categories.
```ruby
form.collection_select :category_id, Category.all, :id, :name
```
--------------------------------
### Complete User Card Component
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/text-and-formatting-helpers.md
A comprehensive example of a `UserCard` component utilizing multiple Phlex::Rails helpers for formatting and dynamic class generation.
```ruby
class UserCard < Phlex::HTML
include Phlex::Rails::Helpers::Truncate
include Phlex::Rails::Helpers::NumberToCurrency
include Phlex::Rails::Helpers::TimeAgoInWords
include Phlex::Rails::Helpers::DOMClass
include Phlex::Rails::Helpers::DOMID
include Phlex::Rails::Helpers::ClassNames
def initialize(user)
@user = user
end
def view_template
classes = class_names(
"user-card",
{ "premium" => @user.premium? }
)
article(id: dom_id(@user), class: classes) do
h3 { @user.name }
p { truncate(@user.bio, length: 150) }
p(class: "meta") do
"Member since #{@user.created_at.strftime('%B %Y')}"
end
p(class: "balance") do
"Balance: #{number_to_currency(@user.account_balance)}"
end
end
end
end
```
--------------------------------
### Nested Form Builder Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/builder.md
Demonstrates how to use nested builders with `fields_for` to create complex form structures. The `comment_form` is also a Builder proxy.
```ruby
class NestedForm < Phlex::HTML
def view_template
form_with(model: @post) do |form|
form.fields_for :comments do |comment_form|
# comment_form is also a Builder proxy
comment_form.text_area :body
end
end
end
end
```
--------------------------------
### Safely Accessing view_context During Rendering
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/errors.md
This example demonstrates the correct approach to accessing `view_context` and its methods, such as `current_user`, by ensuring it's done within the rendering context, typically guarded by `rendering?`.
```ruby
class Component < Phlex::HTML
def view_template
# ✓ Correct: accessed during rendering
if rendering? && view_context.respond_to?(:current_user)
p { "User: #{view_context.current_user.name}" }
end
end
end
```
--------------------------------
### Render Partial within ViewComponent
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/partial.md
This example illustrates rendering a Phlex partial from within a ViewComponent. The partial is rendered using the ViewComponent's view context.
```ruby
class MyViewComponent < ViewComponent::Base
def call
render_in(helpers) do
"ViewComponent-based Phlex"
end
end
def view_template
render(partial("shared/card"))
end
end
```
--------------------------------
### Usage of DOMClass and DOMID Helpers
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/text-and-formatting-helpers.md
Example demonstrating the use of dom_id and dom_class helpers to generate unique IDs and classes for HTML elements based on an object.
```ruby
include Phlex::Rails::Helpers::DOMClass
include Phlex::Rails::Helpers::DOMID
def view_template
user = @current_user
div(id: dom_id(user), class: dom_class(user)) do
@current_user.name
end
end
```
--------------------------------
### Usage of TimeTag Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/text-and-formatting-helpers.md
Example of using the time_tag helper to generate an HTML time element with a specific datetime and content.
```ruby
time_tag(Time.now, "Just now")
# =>
```
--------------------------------
### RichTextArea Usage Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Demonstrates using the `rich_text_area` helper within a `form_with` block for an article's body field.
```ruby
include Phlex::Rails::Helpers::RichTextArea
def view_template
form_with(model: @article) do |form|
form.rich_text_area :body
end
end
```
--------------------------------
### Example: Rendering Partial Rows in a List
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/partial.md
Illustrates using Phlex::Rails::Partial to render individual item rows within a list component. Each partial is rendered within a list item element using the provided view context.
```ruby
class ListComponent < Phlex::HTML
def view_template
ul do
@items.each do |item|
partial = Phlex::Rails::Partial.new("item_row", item: item)
li { partial.render_in(view_context) }
end
end
end
end
```
--------------------------------
### Default Phlex Initializer
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/configuration.md
A default initializer for Phlex is usually not required as the library loads automatically. This is an example of what an empty initializer might look like.
```ruby
# Default configuration - usually empty as Phlex Rails works out of the box
```
--------------------------------
### Direct Form Builder Access Example
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/builder.md
Shows direct access to the `Phlex::Rails::Builder` proxy (`f`) for creating form elements like labels, text fields, and submit buttons within a form.
```ruby
class LoginForm < Phlex::HTML
def view_template
form_with(local: true) do |f|
# f is a Phlex::Rails::Builder
div(class: "form-group") do
f.label :email
f.email_field :email, class: "form-control"
end
div(class: "form-group") do
f.label :password
f.password_field :password, class: "form-control"
end
f.submit "Sign In", class: "btn btn-primary"
end
end
end
```
--------------------------------
### Organize Helpers by Feature in Components
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/configuration.md
Group related helpers within specific component classes to maintain organization. This example shows helpers for form elements.
```ruby
class FormComponent < ApplicationComponent
include Phlex::Rails::Helpers::FormWith
include Phlex::Rails::Helpers::TextField
include Phlex::Rails::Helpers::SubmitTag
include Phlex::Rails::Helpers::Label
end
```
--------------------------------
### Correctly Using Rails Helpers in view_template
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/errors.md
This corrected example shows the proper way to use Rails view helpers by calling them within the `view_template` method, ensuring the view context is available during the rendering process.
```ruby
class GoodComponent < Phlex::HTML
include Phlex::Rails::Helpers::LinkTo
def view_template
# ✓ Correct: called during rendering
p { link_to("Text", "/path") }
end
end
```
--------------------------------
### Create and Render Partial via Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/partial.md
Use the `partial` helper to create and render a partial component, passing locals as keyword arguments. This is the preferred method for creating partials.
```ruby
class DashboardComponent < Phlex::HTML
def view_template
section do
# Creates and renders a partial
render(partial("shared/header", title: "Dashboard"))
article do
# Another partial
render(partial("dashboard/widgets"))
end
end
end
end
```
--------------------------------
### Using the Cycle Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/text-and-formatting-helpers.md
Demonstrates how to use the `cycle` helper to alternate CSS classes for list items.
```ruby
include Phlex::Rails::Helpers::Cycle
def view_template
ul do
@items.each do |item|
li(class: cycle("odd", "even")) do
item.name
end
end
end
end
```
--------------------------------
### Usage of Collection Checkboxes
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Example of using `collection_checkboxes` to generate checkboxes for a collection of roles.
```ruby
form.collection_checkboxes :roles, Role.all, :id, :name do |b|
# b is a builder
b.label { b.check_box + b.text }
end
```
--------------------------------
### Layout with Components
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
Illustrates how to integrate Phlex components within a layout structure, passing data to them during initialization.
```ruby
class BlogLayout < Phlex::HTML
include Phlex::Rails::Layout
def initialize(blog)
@blog = blog
end
def view_template
html do
body do
render(HeaderComponent.new(@blog))
div(class: "blog-container") do
article { render(:content) }
aside { render(SidebarComponent.new(@blog)) }
end
render(FooterComponent.new)
end
end
end
end
```
--------------------------------
### Inspect Phlex::Rails::Builder
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/builder.md
Get a string representation of the builder, useful for debugging purposes.
```ruby
builder = Phlex::Rails::Builder.new(form_builder, component: self)
puts builder.inspect # => Phlex::Rails::Builder(#)
```
--------------------------------
### Register ImageTag Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
Registers the image_tag output helper. This is typically part of the Phlex Rails setup.
```ruby
module Phlex::Rails::Helpers::ImageTag
register_output_helper def image_tag(...) = nil
end
```
--------------------------------
### Instantiate Phlex::Rails::Partial
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/partial.md
Create a Phlex::Rails::Partial object by providing the path to the partial template and any necessary arguments or locals.
```ruby
Phlex::Rails::Partial.new("shared/card", item: @item)
```
--------------------------------
### Create and Render Phlex Partial
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/sgml.md
Use the `partial` method to create a renderable Phlex partial object. Pass the path to the partial and any arguments or locals.
```ruby
partial(path, *args, **kwargs, &block) -> Phlex::Rails::Partial
```
```ruby
class ListComponent < Phlex::HTML
def view_template
ul do
@items.each do |item|
li { render partial("item", item: item) }
end
end
end
end
```
--------------------------------
### Usage of ClassNames Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/text-and-formatting-helpers.md
Example of using the class_names helper to conditionally apply CSS classes to an HTML element.
```ruby
include Phlex::Rails::Helpers::ClassNames
def view_template
classes = class_names("btn", { "btn-primary" => true, "btn-lg" => @large })
button(class: classes) { "Click me" }
end
```
--------------------------------
### Use WordWrap Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/text-and-formatting-helpers.md
Shows how to use the `word_wrap` helper to format text with a specified line width.
```ruby
word_wrap("Long text here...", line_width: 80)
```
--------------------------------
### Usage of TimeAgoInWords Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/text-and-formatting-helpers.md
Example of using the time_ago_in_words helper within a view template to display relative time.
```ruby
include Phlex::Rails::Helpers::TimeAgoInWords
def view_template
p { "Posted #{time_ago_in_words(@article.created_at)} ago" }
# => "Posted 2 days ago"
end
```
--------------------------------
### Get Layout Identifier
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
Returns a unique string identifier for the layout, which is typically the class name of the layout component.
```ruby
ApplicationLayout.identifier
```
--------------------------------
### Equivalent Partial with Block Creation
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/partial.md
This shows the direct equivalent of creating a partial with a block, capturing the block content and passing it to the `Phlex::Rails::Partial` constructor.
```ruby
partial = Phlex::Rails::Partial.new(
"shared/modal",
title: "Confirm"
) { capture { "Are you sure you want to proceed?" } }
render(partial)
```
--------------------------------
### Create and Render Partial Inline
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/partial.md
For greater control, instantiate `Phlex::Rails::Partial` directly and then render it. This allows for passing locals and managing the partial's lifecycle explicitly.
```ruby
class ProductComponent < Phlex::HTML
def initialize(product)
@product = product
end
def view_template
div(class: "product") do
# Create partial with locals
card_partial = Phlex::Rails::Partial.new(
"products/card",
product: @product,
show_price: true
)
# Render in current view context
render(card_partial)
end
end
end
```
--------------------------------
### Get Layout Instance Identifier
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
Retrieves the identifier for a layout instance, which is its class name. This method is useful for introspection or debugging.
```ruby
layout_instance.identifier
```
--------------------------------
### Creating and Using a Buffered Instance
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/buffered.md
Shows how to instantiate `Phlex::Rails::Buffered` and use its methods, such as `content_tag`, to capture and render HTML content within a component. This pattern is useful for generating HTML strings without complex block interactions.
```ruby
class MyComponent < Phlex::HTML
def view_template
buffered = Phlex::Rails::Buffered.new(view_context, component: self)
buffered.content_tag(:div, class: "wrapper") do
"Content goes here"
end
end
end
```
--------------------------------
### Usage of AudioTag Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
Shows how to use the audio_tag helper to embed audio files with controls.
```ruby
include Phlex::Rails::Helpers::AudioTag
def view_template
audio_tag("music.mp3", controls: true)
end
```
--------------------------------
### Using Image Path Helper in a View
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
Demonstrates how to include and use the `image_path` helper within a Phlex view template to generate an image tag.
```ruby
include Phlex::Rails::Helpers::ImagePath
def view_template
img(src: image_path("icon.png"), alt: "Icon")
end
```
--------------------------------
### Use SimpleFormat Helper in a Component
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/text-and-formatting-helpers.md
Demonstrates using the `simple_format` helper to convert a user's bio text into HTML paragraphs within a Phlex component.
```ruby
include Phlex::Rails::Helpers::SimpleFormat
def view_template
# Converts text to HTML paragraphs
simple_format(@user_bio)
end
```
--------------------------------
### Get Layout Virtual Path
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
Retrieves the virtual path for a layout instance, represented as an underscore-separated string. This is commonly used in Rails for view resolution.
```ruby
layout_instance.virtual_path
```
--------------------------------
### Usage of PreloadLinkTag Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
Demonstrates using preload_link_tag to specify resources that should be preloaded, such as fonts and images.
```ruby
preload_link_tag("fonts/roboto.woff2", as: "font", type: "font/woff2")
preload_link_tag("/images/large.png", as: "image")
```
--------------------------------
### Raise HelpersCalledBeforeRenderError
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/sgml.md
Raise an error when attempting to access Rails view helpers before the component rendering process has started. This ensures proper lifecycle management.
```ruby
raise Phlex::Rails::HelpersCalledBeforeRenderError.new(
"You can't use Rails view helpers until after the component has started rendering."
)
```
--------------------------------
### Usage of VideoTag Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
Demonstrates using the video_tag helper to embed video files with specified dimensions and controls.
```ruby
include Phlex::Rails::Helpers::VideoTag
def view_template
video_tag("movie.mp4", width: 640, height: 480, controls: true)
end
```
--------------------------------
### Rendering Partials and Components
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/sgml.md
Shows how to render other Phlex components and Rails partials within a layout component. Uses `render` for components and `render(partial: ...)` for partials.
```ruby
class DashboardLayout < Phlex::HTML
def initialize(user)
@user = user
end
def view_template
div(class: "dashboard") do
render(HeaderComponent.new(@user))
render(partial("sidebar"))
div(class: "content") { yield }
end
end
end
```
--------------------------------
### ViewComponent Integration with Phlex
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/configuration.md
Shows how to integrate Phlex views within a ViewComponent using `render_in` and the `helpers` object.
```ruby
class MyViewComponent < ViewComponent::Base
include Phlex::Rails::SGML
def call
render_in(helpers) do
# Phlex view template
end
end
def view_template
div { "Content" }
end
end
```
--------------------------------
### Get Layout Virtual Path
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
Returns the virtual path of the layout, used by Rails for template resolution. The path is derived from the class name by converting it to snake_case.
```ruby
ApplicationLayout.virtual_path
```
--------------------------------
### Get Capture Context
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/sgml.md
The `capture_context` method returns the appropriate capture context for the current rendering situation, ensuring `capture` works correctly in different contexts.
```ruby
capture_context() -> Object
```
--------------------------------
### render_in
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/sgml.md
The core method called by Rails to render the component, handling view context setup, fragment caching, and executing the component's view template.
```APIDOC
## render_in
### Description
Core method called by Rails to render the component. It sets up the view context, handles fragment caching if the `X-Fragments` header is present, and executes the component's `view_template` method, returning an HTML-safe string.
### Method
`render_in(view_context, **options, &erb) -> String`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```ruby
class MyComponent < Phlex::HTML
def view_template
div { @title }
end
end
# Called from controller or template
rendered = MyComponent.render_in(view_context)
# => HTML-safe string
```
### Response
#### Success Response
Rendered HTML string marked as safe.
#### Response Example
None provided.
```
--------------------------------
### Inspect Buffered Object
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/buffered.md
Get a string representation of the Phlex::Rails::Buffered object for debugging purposes. The output includes the inspect string of the underlying wrapped object.
```ruby
buffered = Phlex::Rails::Buffered.new(helper_object, component: self)
puts buffered.inspect # => Phlex::Rails::Buffered(#)
```
--------------------------------
### Usage of ImageTag Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
Demonstrates how to use the image_tag helper to render image elements with attributes like alt, class, and size.
```ruby
include Phlex::Rails::Helpers::ImageTag
def view_template
image_tag("logo.png", alt: "Logo", class: "logo")
image_tag("avatar.jpg", size: "50x50")
end
```
--------------------------------
### Generate Phlex Rails Components
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/configuration.md
Use Rails generators to quickly scaffold Phlex components, views, or install Phlex Rails. No explicit configuration is needed as generators work automatically.
```bash
rails generate phlex:component MyComponent
rails generate phlex:view PostsIndex
rails generate phlex:install
```
--------------------------------
### Instantiate Buffered Proxy
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/buffered.md
Create a new Buffered instance, wrapping an object and associating it with a Phlex component for rendering context. This is often used internally by helper registration.
```ruby
Buffered.new(rails_object, component: self)
```
```ruby
class MyComponent < Phlex::HTML
def view_template
# Most commonly used through helper registration
buffered = Phlex::Rails::Buffered.new(view_context.helpers, component: self)
end
end
```
--------------------------------
### Using Buffered Helpers in a Component
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/buffered.md
Demonstrates how to include and use buffered helpers like `link_to` within a Phlex component. These helpers are designed for simple method calls that return HTML strings.
```ruby
class MyComponent < Phlex::HTML
include Phlex::Rails::Helpers::LinkTo
def view_template
div do
# link_to is registered as a buffered helper
link_to "Click Me", "/path"
link_to "Another Link", "/other"
end
end
end
```
--------------------------------
### Create Custom Rails Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/configuration.md
Demonstrates how to define and use a custom output helper within a Phlex component in Rails.
```ruby
module Phlex::Rails::Helpers::MyCustomHelper
extend Phlex::Rails::HelperMacros
register_output_helper def my_helper(...) = nil
end
# Use in component
class MyComponent < Phlex::HTML
include Phlex::Rails::Helpers::MyCustomHelper
def view_template
my_helper(arg)
end
end
```
--------------------------------
### Triggering HelpersCalledBeforeRenderError in Initializer
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/errors.md
This example demonstrates how calling a Rails view helper like `link_to` within the `initialize` method of a Phlex component leads to a `HelpersCalledBeforeRenderError` because the view context is not yet available.
```ruby
class BadComponent < Phlex::HTML
include Phlex::Rails::Helpers::LinkTo
def initialize
# ❌ Error: view_context not available yet
@path = link_to("Text", "/path")
end
def view_template
p { @path }
end
end
```
--------------------------------
### Use Highlight Helper in a Component
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/text-and-formatting-helpers.md
Demonstrates using the `highlight` helper to visually emphasize search terms in text, wrapping them in `` tags.
```ruby
include Phlex::Rails::Helpers::Highlight
def view_template
# Highlights search terms in text
p { highlight("Hello world", "world") }
# => "Hello world"
end
```
--------------------------------
### partial
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/sgml.md
Creates a partial rendering object that can be rendered as a Phlex component. It accepts a path to the partial template and any arguments or blocks to be passed.
```APIDOC
## partial(path, *args, **kwargs, &block) → Phlex::Rails::Partial
### Description
Creates a partial rendering object that can be rendered as a Phlex component. It accepts a path to the partial template and any arguments or blocks to be passed.
### Parameters
* **path** (String/Symbol) - Required - Path to the partial template
* **args** (Array) - Optional - Positional arguments passed to the partial
* **kwargs** (Hash) - Optional - Keyword arguments (locals) passed to the partial
* **block** (Proc) - Optional - Block to yield in the partial
### Returns
`Phlex::Rails::Partial` instance (renderable in view templates)
### Example
```ruby
class ListComponent < Phlex::HTML
def view_template
ul do
@items.each do |item|
li { render partial("item", item: item) }
end
end
end
end
```
```
--------------------------------
### Create Application Component Base
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/configuration.md
Establish a base component class inheriting from Phlex::HTML to include common helpers and configurations. Other components can then inherit from this base.
```ruby
# app/components/application_component.rb
class ApplicationComponent < Phlex::HTML
include Phlex::Rails::Helpers::LinkTo
include Phlex::Rails::Helpers::ImageTag
# Include common helpers here
end
class MyComponent < ApplicationComponent
# Inherits common helpers
end
```
--------------------------------
### Unwrap Phlex Proxy Objects
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/types.md
Demonstrates how to use Phlex::Rails::Types.Buffered and Phlex::Rails::Types.Builder to check if an object is a proxy and then unwrap it to get the original object. Useful when you need to interact with the underlying object.
```ruby
buffered_form = Phlex::Rails::Types.Buffered(ActionView::Helpers::FormBuilder)
builder_form = Phlex::Rails::Types.Builder(ActionView::Helpers::FormBuilder)
if buffered_form.call(obj)
original = obj.unwrap # Get the original object
end
if builder_form.call(obj)
original = obj.unwrap # Get the FormBuilder
end
```
--------------------------------
### Use Excerpt Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/text-and-formatting-helpers.md
Shows how to extract an excerpt around a specific phrase using the `excerpt` helper.
```ruby
# Extract excerpt around a phrase
excerpt("Hello world, this is great", "world", radius: 5)
# => "...Hello world, this..."
```
--------------------------------
### Integrating SGML into a ViewComponent
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/sgml.md
Include the `Phlex::Rails::SGML` module in your ViewComponent class to leverage SGML's rendering capabilities. This setup ensures correct view context and rendering delegation through the ViewComponent system.
```ruby
class MyViewComponent < ViewComponent::Base
include Phlex::Rails::SGML
def call
render_in(helpers)
end
def view_template
div { "ViewComponent-integrated Phlex" }
end
end
```
--------------------------------
### Creating a Rails Layout Component with Phlex::Rails::Layout
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
This snippet demonstrates how to create a basic Rails application layout using Phlex::HTML and including the Phlex::Rails::Layout module. It shows the integration of standard Rails helpers like `csrf_meta_tags` and `javascript_include_tag` within the Phlex template.
```ruby
class ApplicationLayout < Phlex::HTML
include Phlex::Rails::Layout
def view_template
html do
head do
# layout helpers available here
csrf_meta_tags
javascript_include_tag "application"
end
body do
# :content is yielded from Rails controller
render(:content)
end
end
end
end
```
--------------------------------
### Buffered.new
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/buffered.md
Initializes a new Buffered instance. This acts as a proxy to an underlying object, capturing its method outputs as HTML-safe content within the Phlex rendering context.
```APIDOC
## Buffered.new(object, component:)
### Description
Initializes a new Buffered instance. This acts as a proxy to an underlying object, capturing its method outputs as HTML-safe content within the Phlex rendering context.
### Parameters
#### Path Parameters
- **object** (Object) - Required - The underlying object whose methods should return safe HTML
- **component** (Phlex::HTML/SVG) - Required - The Phlex component that owns this buffered object, used for rendering context
### Returns
`Phlex::Rails::Buffered` instance
### Example
```ruby
class MyComponent < Phlex::HTML
def view_template
# Most commonly used through helper registration
buffered = Phlex::Rails::Buffered.new(view_context.helpers, component: self)
end
end
```
```
--------------------------------
### Registering an Output Helper (ImageTag)
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/helper-macros.md
Demonstrates how to register an output helper like `image_tag` within a helper module. This macro generates a method that calls the Rails helper and wraps its output.
```ruby
# In a helper module
module Phlex::Rails::Helpers::ImageTag
extend Phlex::Rails::HelperMacros
register_output_helper def image_tag(...) = nil
end
# Usage
class Header < Phlex::HTML
include Phlex::Rails::Helpers::ImageTag
def view_template
image_tag("logo.png", alt: "Logo")
end
end
# Generated equivalent (simplified)
def image_tag(*args, **kwargs, &block)
output = if block
view_context.image_tag(*args, **kwargs) { |*args| capture(*args, &block) }
else
view_context.image_tag(*args, **kwargs)
end
raw(output)
end
```
--------------------------------
### Initialize Phlex::Rails::Builder
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/builder.md
Instantiate a new Builder by passing the underlying Rails form builder object and the owning Phlex component.
```ruby
Builder.new(form_builder, component: self)
```
--------------------------------
### Create a Phlex Layout Component
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/README.md
Implement layout components by inheriting from Phlex::HTML and including Phlex::Rails::Layout to manage page structure and content yielding.
```ruby
class ApplicationLayout < Phlex::HTML
include Phlex::Rails::Layout
def view_template
html do
body do
header { render(:nav) }
main { render(:content) }
footer { "© 2024" }
end
end
end
end
```
--------------------------------
### Basic Application Layout
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/layout.md
A fundamental layout structure for a Rails application using Phlex::Rails::Layout. Includes common head and body elements.
```ruby
class ApplicationLayout < Phlex::HTML
include Phlex::Rails::Layout
def view_template
html(lang: "en") do
head do
meta(charset: "utf-8")
meta(name: "viewport", content: "width=device-width, initial-scale=1")
title { "My App" }
csrf_meta_tags
javascript_include_tag "application", "data-turbo-track": "reload"
stylesheet_link_tag "application", "data-turbo-track": "reload"
end
body do
header { render(:nav) }
main { render(:content) }
footer { "© 2024" }
end
end
end
end
```
--------------------------------
### Phlex Rails Project Structure
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/overview.md
Illustrates the directory structure of the phlex-rails gem, highlighting key files and modules for entry points, core logic, and helper implementations.
```text
lib/
├── phlex-rails.rb # Entry point
├── phlex/rails.rb # Main module setup with Zeitwerk loader
├── phlex/rails/
│ ├── version.rb # Version constant
│ ├── builder.rb # Builder class for form helpers
│ ├── buffered.rb # Buffered proxy for safe HTML
│ ├── csv.rb # CSV generation support
│ ├── helper_macros.rb # Macros for registering Rails helpers
│ ├── helpers.rb # Helpers module and redirects
│ ├── layout.rb # Layout module for templates
│ ├── partial.rb # Partial rendering support
│ ├── sgml.rb # SGML/HTML rendering logic
│ ├── sgml/state.rb # SGML rendering state
│ ├── types.rb # Type validation helpers
│ ├── never.rb # Never modifier for conditional rendering
│ └── helpers/ # 200+ individual helper modules
│ ├── form_with.rb
│ ├── link_to.rb
│ ├── image_tag.rb
│ ├── ... (200+ Rails helper adapters)
```
--------------------------------
### Configure Application Layout with Phlex
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/configuration.md
Define a layout component using Phlex::HTML and Phlex::Rails::Layout. Configure Rails to use this layout by setting `config.layout`.
```ruby
# app/layouts/application_layout.rb
class ApplicationLayout < Phlex::HTML
include Phlex::Rails::Layout
def view_template
html do
head { javascript_include_tag "application" }
body { render(:content) }
end
end
end
# config/application.rb
config.layout = "application"
```
--------------------------------
### Core Rails Rendering with `render_in`
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/sgml.md
The `render_in` method is the primary entry point for Rails to render a Phlex component. It sets up the view context, handles fragment caching, and executes the component's `view_template`. It returns an HTML-safe string.
```ruby
render_in(view_context, **options, &erb) -> String
```
```ruby
class MyComponent < Phlex::HTML
def view_template
div { @title }
end
end
# Called from controller or template
rendered = MyComponent.render_in(view_context)
# => HTML-safe string
```
--------------------------------
### URLToVideo Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/link-and-url-helpers.md
The `url_to_video` helper generates a URL string for a video asset. It is not an HTML helper and returns a URL string.
```ruby
module Phlex::Rails::Helpers::URLToVideo
register_value_helper def url_to_video(...) = nil
end
```
--------------------------------
### Register Output Helper
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/configuration.md
Registers a helper that returns an HTML string. The output is automatically wrapped with `raw()` for safety.
```ruby
register_output_helper def helper_name(...) = nil
```
--------------------------------
### Define Component Output Format
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/sgml.md
Specify the output format for a component. Use :html for standard HTML components or :svg for SVG components.
```ruby
def format
:html # or :svg for SVG components
end
```
--------------------------------
### OptionsForSelect and OptionsFromCollectionForSelect
Source: https://github.com/yippee-fun/phlex-rails/blob/main/_autodocs/api-reference/form-helpers.md
Helpers for generating HTML option tags for select elements.
```APIDOC
## OptionsForSelect / OptionsFromCollectionForSelect
### Description
These helpers generate the HTML `