3

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?

5

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 %}
|improve this answer|||||
  • Tried the suggestions above, it does not filter out those fields. So it still prints twice. Does '|without' work on 'field'? – heart.cooks.mind Jan 31 '17 at 20:19
  • Actually that did fix it. drush cr lol. Thank you! – heart.cooks.mind Jan 31 '17 at 20:25
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.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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