6

I want to theme the display of a Views based on the Content type. In my attempts to do that, I’ve created the views showing All Content Types. I’ve added all the fields I need, and also included a Content: Type field. It is this field that I am trying to use for conditionally formatting the output (if it’s a Blog content type use this html and for all other content types use a different html).

This is what I have tried so far but that condition is not triggering at all

I have created a views-view-fields--myexample.html.twig

{% if fields.type.content == 'blog' %}
<div class="blog-content views-row">
  <div class="showcase" style="background-color: {{ fields.field_color.content }};">

</div>
{% else %}

<div class="other-content views-row">
   <div class="showcase">
   {{ fields.title.content}}
   {{ fields.field_image.content }}
   </div>
</div>
{% endif %}
2

Probably because {{ fields.type.content }} = <div class="something">blog</div>

so try

{% if fields.type.content|striptags == {{ 'blog'|t }} %}

If you do not want to have to use |striptags you could strip the markup from the Views UI.

Also, do not check mark Exclude from display in configure field, because if you do this your template file will not have access to that field.

Side note: you forgot to close the div in line 3.


Alternatively

{% if row._entity.gettype == 'content_type_machine_name' %}

alternate method credit: 4K4

  • 1
    Good advice for fields in general. For the content type there is an alternative option, you can get the id directly from the entity: {{ row._entity.gettype }}. Then you don't depend on that the field is configured correctly in UI (what if it gets translated?). – 4k4 Jan 26 '17 at 8:01
  • @4k4, good point, updated my answer to cover for translations. – No Sssweat Jan 26 '17 at 9:03

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.