I am trying to customize a views output on a view page to wrap the fields in custom markup. I need to group a set of fields to achieve the desired layout like so:


   <div class="wrapper">
       {{ field.[field_name_1].content }}
   <div class="wrapper2">
       {{ field.[field_name_2].content }}
       {{ field.[field_name_3].content }}
       {{ field.[field_name_4].content }}

This is what I have come up with so far:

{% if view.projects_page -%}    
    <div class="project-img columns large-8 medium-12 small-12">
        {{ field.field_project_image.content }}
    <div class="description columns large-4 medium-10 small-12">
        {{ field.field_project_header.content }}
        {{ field.field_sub_header.content }}
        {{ field.field_short_project_description.content }}
{%- endif %}

This doesn't throw any errors but also doesn't seem to work because {% if view.projects_page -%} does not target the view in the way I thought it would.

So the question is - How do I detect the view with a conditional so I get the output desired above?


You need to refer documentation for the working with twig template. Here you can use conditional twig :

Twig: {% if field.[field_name].content is not empty %} field.[field_name].content {% endif %}

| improve this answer | |
  • Thank you for the response. The link has been helpful but the code provided still throws errors. Odd because it appears as if it should work. I double checked the field machine name and that is not the problem so I'm gonna keep reading. – KRC Aug 31 '16 at 17:42

Sorry, but this is confusing me. Do you really mean views-view-fields.html.twig?
Because you reach the fields like
{{ fields.[field_name].content }} and not
{{ field.[field_name].content }} and inside the "for" you can test with
{% if field == fields.[field_name] }}

Ah and try

{{ kint(row.[field_name] ,row._entity.get('[field_name]').value) }}

Because when you need to check for a value and you have twig in development mode (literally spoken:
twig.config: debug: true
) you will get the template suggestions in field.content. So when you are checking for the nid it would be
{% if row.nid == 900 %} Do someting {% endif %}

| 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.