Using conditional Twig logic in Views replacement patterns in Drupal 8
If you are using fields to display content in a View, you can do some of the things in Replacement Patterns as you can do in a theme template.
Note: There are likely other ways to do this, including maybe Display Suite or the theme layer. But this is an example of how this can be done in Views. Don’t @ me. ;)
Example
Here is a bare-bones, simple example.
I have a content type. I have a View. I want to display certain fields from that content type in an HTML component. There is some HTML I don’t want to show if the field is empty.
Here is a hypothetical HTML component.
<div class="banner"
<div class="banner-image"><img src="mybanner.jpg"></div>
<div class="banner-caption-wrapper">
<div class="banner-caption">My caption</div>
<div class="banner-button"><a href="link">My button</a></div>
</div>
</div>
The bolded code would be provided by these hypothetical fields:
- field_banner_image
- field_caption
- field_button
I made my View like this:
- Added each field with the settings I wanted.
- Set to be hidden
- Create Custom text field and make sure it’s last in the list of fields.
- In the Custom text field settings, expanded replacement patterns to get the tokens for my fields.
5. Use the tokens in the HTML
<div class="banner">
<div class="banner-image">{{ field_banner_image }}</div>
<div class="banner-caption-wrapper">
<div class="banner-caption">{{ field_caption }}</div>
<div class="banner-button">{{ field_button }}</div>
</div>
</div>
Use conditional twig logic to hide part of the component
“If there is a caption, show the caption HTML.”
Or, “if the caption is empty, don’t show the caption’s HTML”.
<div class="banner">
<div class="banner-image">{{ field_banner_image }}</div<
<div class="banner-caption-wrapper">
{% if field_caption %}
<div class="banner-caption">{{ field_caption }}</div>
{% endif %}
<div class="banner-button">{{ field_button }}</div>
</div>
</div>
You can also use logic operators, like or
.
“If there is a caption or button, show the caption wrapper.”
Or, “if both there is neither a caption nor a button, do not show the caption wrapper.”
<div class="banner">
<div class="banner-image">{{ field_banner_image }}</div<
{% if field_caption or field_button %}
<div class="banner-caption-wrapper">
<div class="banner-caption">{{ field_caption }}</div>
<div class="banner-button">{{ field_button }}</div>
</div>
{% endif %}
</div>