2

I'm having trouble doing something that I think should be relatively simple Drupal 8 views.

I have a content type called Countries. I would like to display the 3 latest country nodes on my homepage in a views block. Each country is displayed with the class "views-row" on the container div. I am using views--view--unformatted--countries--block_1.html.twig to theme the output.

I would like to output something like the following markup:

<a class="view-row-1" href="/link/to/node">
    <img src="source-of-teaser-image.png">
    <h3>Title of node</h3>
</a>

<a class="view-row-2" href="/link/to/node">
    <img src="source-of-teaser-image.png">
    <h3>Title of node</h3>
</a>

<a class="view-row-3" href="/link/to/node">
    <img src="source-of-teaser-image.png">
    <h3>Title of node</h3>
</a>

The problem I'm having is accessing individual fields in the template. If I use a view mode, I can access individual fields. If I select "show fields" in the view, I can add a field for "view result counter" and "path", which would allow me to add the "view-row-N" class and link the a tag to the node, but I can't get access to the fields individually. I have the {{ row.content }} variable, but any attempt to dig further into the variable (eg row.content.field_name) gives me nothing and calling a {{ dump(row.content) }} crashes the website.

I can't output this as a view mode for 2 reasons. I don't have access to the "view result counter" or "path" fields in a view mode and, even if I had these variables, some fields would be nested inside others (The image and title are nested inside the )

I feel this should really be as simple as

<a class="view-row-{{ row.content.view_result_counter }}" href="{{ row.content.path }}">

etc but I've tried everything I can think of. Am I completely on the wrong path?

1 Answer 1

5

You are on the wrong track. If you want to rewrite in twig how the fields are built to a row, you have to use the template views-view-fields.html.twig.

But the simplest method would be to rewrite the result of the fields in views ui. This is the option "Override the output of this field with custom text". If you apply this on the last field and hide all previous fields with the option "Exclude from display", you can see the twig variables for all fields in "Replacement patterns" and you are able to rewrite the complete row like the example you have shown in the question.

0

Your Answer

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

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