3

Using views-view.html.twig as a starting point, I can output {{ rows }}, but I want to loop through each field of each row to aggregate and style them.

In Drupal 7, I use dpm(rows) to locate (in the array) where content, label etc. But kint doesn't seem to provide me the same information. Can anyone help?

  • OK, so I've discovered the template preprocess function for my view, but I'm still unsure how to output specific variables... – RominRonin Jan 21 '16 at 14:01
4

In views-view.html.twig is not appropriate to style your row and fields.

To style them first you need override template "views_view_'format_style'" (format style specified when you edit/create a view). Here you can style row and access 'fields' variables (use kint(row) to see them).

Something like:

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {{ kint(row) }} {# devel #}
  <h2> {{row.content['#node'].getTitle()}} </h2> {# access fields #}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}

For style fields its better override field template.

For example field--node--body--article.html.twig:

{% set mode = element['#view_mode'] %}
{% if label_hidden %}
  {% for item in items %}
    {% if mode == 'full' %}
        <div{{ attributes }}>{{ item.content }}</div>
    {% elseif mode == 'teaser' %}
        <p{{ attributes }}>{{ item.content }}</p>
    {% endif %}
  {% endfor %}
{% else %}
  <div{{ attributes }}>
    <div{{ title_attributes }}>{{ label }}</div>
    {% for item in items %}
      <div{{ item.attributes }}>{{ item.content }}</div>
    {% endfor %}
  </div>
{% endif %}

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.