A themer can easily access desired field values in multiple templates in a conditional-logic-friendly format
User story
Given that I am a designer or developer seeking to customize templates,
when I need to include conditional logic based on a boolean field or other field with non user-entered values
I want to easily access that field so that I can customize output based on the value of that field.
Background
We're trying to avoid grotesque manipulations of code like the below (from a project that diverged from Drutopia, but the client/developer is more than happy to have parts re-incorporated into Drutopia— in this case if we want a very simple 'private content' feature, but that's not the point here).
The same variable is trying to be accessed, with wildly different approaches used, in...
A content template: web/themes/example/templates/content/node--event--micro.html.twig
<a href="{{ url }}" class="card-link"></a>
<div class="card white-background {{ source }} link event micro">
<div class="teaser">
{% if content.private[0]|render|trim == 'Private' %}
<div class="private-content--card">
<i class="icon ion-android-lock icon--dot--small"></i>
</div>
{% endif %}
<div class="flex-media">
<div class="flex-media__image">
<time class="date-box" datetime="{{ event_date }}">
In fields, such as: web/themes/example/templates/field/field--node--private--feed.html.twig
{% if items[0].content['#markup']|render == 'Private' %}
<div class="private-content--card">
<i class="icon ion-android-lock icon--dot--small"></i>
</div>
{% endif %}
And in the content title template, using a preprocessor to make it available:
web/themes/example/example.theme
if ($variables['field_name'] == 'title' && $variables['element']['#object']->hasField('private') && $variables['element']['#view_mode'] != 'micro') {
$private = $variables['element']['#object']->get('private')->getValue();
$variables['private'] = $private[0]['stored'];
}
And in a couple title templates:
web/themes/example/templates/field/field--node--title.html.twig
{% if private == 1 %}
<span class="private-content--node" title="Private Content">
<i class="icon ion-android-lock"></i>
</span>
{% endif %}
<span{{ attributes }}>
{%- for item in items -%}
{{ item.content }}
{%- endfor -%}
</span>
Proposed solution
Ah, i'm more of a problems kind of person...