Visitar URL original
view_component/docs/guide/conditional_rendering.md at main · ViewComponent/view_component · GitHub
Skip to content

Latest commit

 

History

History
54 lines (41 loc) · 1.16 KB

conditional_rendering.md

File metadata and controls

54 lines (41 loc) · 1.16 KB
layout default
title Conditional rendering
parent How-to guide

Conditional rendering

Since 1.8.0 {: .label }

Components can implement a #render? method to be called after initialization to determine if the component should render.

Traditionally, the logic for whether to render a view could go in either the component template:

<% if user.requires_confirmation? %>
  <div class="alert">Please confirm your email address.</div>
<% end %>

or the view that renders the component:

<% if current_user.requires_confirmation? %>
  <%= render(ConfirmEmailComponent.new(user: current_user)) %>
<% end %>

Using the #render? hook simplifies the view:

class ConfirmEmailComponent < ViewComponent::Base
  erb_template <<-ERB
    <div class="banner">
      Please confirm your email address.
    </div>
  ERB

  def initialize(user:)
    @user = user
  end

  def render?
    @user.requires_confirmation?
  end
end
<%= render(ConfirmEmailComponent.new(user: current_user)) %>

To assert whether a component has been rendered, use assert_component_rendered / refute_component_rendered from ViewComponent::TestHelpers.