4

I am overriding the fields template views-view-fields--machine_name.html.twig.

I want to render some Fields in a different div than the other fields. I do not want the fields to render twice.

<div class="foo">
  {{ fields.field_events_date_start.content }}
  {{ fields.field_events_date_start_1.content }}
</div>

{% for field in fields -%}
  {{ field.separator }}
  {%- if field.wrapper_element -%}
    <{{ field.wrapper_element }}{{ field.wrapper_attributes }}>
  {%- endif %}
  {%- if field.label -%}
    {%- if field.label_element -%}
      <{{ field.label_element }}{{ field.label_attributes }}>{{ field.label }}{{ field.label_suffix }}</{{ field.label_element }}>
    {%- else -%}
      {{ field.label }}{{ field.label_suffix }}
    {%- endif %}
  {%- endif %}
  {%- if field.element_type -%}
    <{{ field.element_type }}{{ field.element_attributes }}>{{ field.content }}</{{ field.element_type }}>
  {%- else -%}
    {{ field.content }}
  {%- endif %}
  {%- if field.wrapper_element -%}
    </{{ field.wrapper_element }}>
  {%- endif %}
{%- endfor %}

If I exclude those Fields from the display in Views it hides them both when they render before and in the normal content area.

{{ content|without('field_events_date_start', 'field_events_date_start_1') }}

...Does not work because I am rendering Fields, not content.

How do I get the fields to render before, but be excluded later?

3 Answers 3

11

You would have to remove the two fields from fields.

<div class="foo">
  {{ fields.field_events_date_start.content }}
  {{ fields.field_events_date_start_1.content }}
</div>

{% for field in fields|without('field_events_date_start',  field_events_date_start_1') %}
  ...
{% endfor %}
0
0

Here is an example of this I did last week.

Filename views-view-fields--view_name--display_id.html.twig i.e. views-view-fields--acquia-search--results.html.twig in my case.

{{ fields.title.content }}
<p class="search-result__item-description">{{ fields.search_api_excerpt.content }}</p>
<ul class="search-result__item-meta">
  <li class="search-result__item-link"><span class="label">View More:</span> {{ fields.url.content }}</li>
  <li class="search-result__item-date"><span class="label">Date Modified:</span> {{ fields.changed.content }}</li>
</ul>

I am printing the fields at my discretion and providing my own markup.

If you install Twig XDebug, you can drop {{ breakpoint() }} into your template and see your variables.

-2

Example: in variable 'content' was 10 elements (name, date, id,...) {{ content }} - get all fields {{ content|without('date') }} get all fields(name, (((deleted - date))), id,...), except 'date'

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.