How do you print View fields on Twig?

I have a view and added the title as a field.

For example: How do I print the title?

In Drupal 7 it was as simple as

views-view-fields--[viewname].tpl.php

<?php print $fields["title"]->content; ?>

How do we do this in Drupal 8?

I have created views-view-fields--[viewname].html.twig

I thought it might be {{ fields.title }} but I get the classic error message like so:

The website encountered an unexpected error. Please try again later.

I then tried {{ field.title }}, {{ title }} and {{ content.title }} but nothing prints.

Answers 3

  • After eating dinner, washing the dishes, playing around with it and reading the comments in views-view-fields.html.twig located in core\modules\views\templates

    /**
     * @file
     * Theme override to display all the fields in a row.
     *
     * Available variables:
     * - view: The view in use.
     * - fields: A list of fields, each one contains:
     *   - content: The output of the field.
     *   - raw: The raw data for the field, if it exists. This is NOT output safe.
     *   - class: The safe class ID to use.
     *   - handler: The Views field handler controlling this field.
     *   - inline: Whether or not the field should be inline.
     *   - wrapper_element: An HTML element for a wrapper.
     *   - wrapper_attributes: List of attributes for wrapper element.
     *   - separator: An optional separator that may appear before a field.
     *   - label: The field's label text.
     *   - label_element: An HTML element for a label wrapper.
     *   - label_attributes: List of attributes for label wrapper.
     *   - label_suffix: Colon after the label.
     *   - element_type: An HTML element for the field content.
     *   - element_attributes: List of attributes for HTML element for field content.
     *   - has_label_colon: A boolean indicating whether to display a colon after
     *     the label.
     *   - element_type: An HTML element for the field content.
     *   - element_attributes: List of attributes for HTML element for field content.
     * - row: The raw result from the query, with all data it fetched.
     *
     * @see template_preprocess_views_view_fields()
     */
    

    {{ fields.title.content }} worked for me. In hindsight it's very similar to the D7 code, duh, lol.

    For other fields:

    {{ fields.machine_name.content }} What's the machine name? You can find them under the Machine Name column in the Manage Fields of your content type or block.


  • I have figured a way using kint.

    Inside your views-view-unformatted.html.twig use the following code to display your individual fields:

    {% for row in rows %}
    
    {{ row.content['#view'].style_plugin.render_tokens[ loop.index0 ]['{{ YOUR_FIELD_NAME }}'] }}
    
    {% endfor %}
    


Related Questions