Drupal 8 Twig自定义视图模板:字段输出与分类术语检测问题
Hey there! Let's work through your Drupal 8 Twig template issues one by one—first fixing those missing fields, then figuring out how to check for that "webinar" term.
1. Why Your Fields Aren't Showing Up (and How to Fix It)
First, let's make sure your view is set up correctly to pass those fields to your template:
- Head into your view's edit screen, and add
field_event_type,field_date, andfield_locationto the Fields section. - For each of these fields, check the Exclude from display option. This tells Drupal not to render them automatically, but still makes their data available for you to use in your Twig template.
The content array can be finicky in view templates—instead, it's more reliable to pull field values directly from the entity object using row._entity. Here's how to update your code:
Example for Single-Value Fields
<h4>{{ label }}</h4> {# For taxonomy fields: grab the term name #} <p>{{ row._entity.field_event_type.entity.name.value }}</p> <p> {# Format the date (adjust the date string to match your needs) #} {{ row._entity.field_date.value|date('F j, Y') }} <br> {# For text/location fields: pull the raw value #} {{ row._entity.field_location.value }} </p> <a href="{{ url }}" aria-label="" class="btn btn-primary my-2 p-3">Read event details</a>
If you want to keep Drupal's default field formatting (like proper date rendering or address formatting), use the |view filter to render the full field:
<p>{{ row._entity.field_event_type|view }}</p> <p> {{ row._entity.field_date|view }} <br> {{ row._entity.field_location|view }} </p>
2. Checking if the Taxonomy Field Contains the "Webinar" Term
The has_term() method you tried doesn't work on the content array because that's a render array, not an entity reference. Instead, we'll pull the taxonomy terms directly from the entity and check them:
For Single-Value Taxonomy Fields
If field_event_type only allows one term, you can check directly:
{% if row._entity.field_event_type.entity.name.value == 'webinar' %} <p>Is webinar</p> {% endif %}
For Multi-Value Taxonomy Fields
If the field allows multiple terms, loop through each term to check:
{% set is_webinar = false %} {% for term in row._entity.field_event_type %} {% if term.entity.name.value == 'webinar' %} {% set is_webinar = true %} {% break %} {# Exit the loop early once we find a match #} {% endif %} {% endfor %} {% if is_webinar %} <p>Is webinar</p> {% endif %}
Pro tip: Using the term ID instead of the name is more reliable (since term names can be changed). If your "webinar" term has an ID of, say, 5, you can do this:
{% if row._entity.field_event_type.target_id == 5 %} <p>Is webinar</p> {% endif %}
内容的提问来源于stack exchange,提问作者Martyn

