File: conditional_rendering.md

package info (click to toggle)
ruby-view-component 4.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,832 kB
  • sloc: ruby: 8,385; sh: 166; makefile: 4
file content (54 lines) | stat: -rw-r--r-- 1,183 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
---
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:

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

or the view that renders the component:

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

Using the `#render?` hook simplifies the view:

```ruby
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
```

```erb
<%= render(ConfirmEmailComponent.new(user: current_user)) %>
```

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