2

I have an view that uses the Unformatted list format and Show: fields.

enter image description here

I've added the fields to it and the view has _Content type: my_content_type_ filter.

I want to write a template file for the fields in that view, with the following code.

{% if field_name == 'field_photo' %}
    ...
{% elseif field_name == 'field_something_else' %}
<div class="something">
    {% for item in items %}
        {{ item.content }}
    {% endfor %}
</div><!-- .something -->

I don't know which name to use for the template file.

I've tried the following names, but they don't work. MY_CUSTOM_TYPE stays for the content type I have set in filter for that view.

  • field--MY_CUSTOM_TYPE.html.twig
  • field--node--MY_CUSTOM_TYPE.html.twig

What is the correct filename for the template file I am trying to use?

2
  • Did you enable twig debugging and look at the suggestions?
    – Kevin
    Jan 21, 2017 at 18:24
  • @Kevin yes, and there are no suggestions for it (on such deep level) - they exists only for the whole view and not for the separate fields.
    – PolGraphic
    Jan 21, 2017 at 18:30

2 Answers 2

2

You could use:

views-view-fields--[view-name]--[machine-name].html.twig

Use the machine name if you only want to affect a specific view Display. (IE: when you click + Add button, that other view/display does not get affected). If you wan't all displays to be affected, then don't include the machine name.

views-view-fields--[view-name].html.twig

{% if fields.field_photo.content|striptags == 'some value' %}
    ...
{% elseif fields.field_something_else.content|striptags == 'some value' %}
<div class="something-specific">
        {{ fields.field_something_else.content }}
</div><!-- .something-specific -->
{% endif %}

If you just want to add a div class regardless of the value of the field and not depending on some condition, then simply

<div class="something">{{ fields.field_machine_name.content }}</div>

OR you can do this through the Views UI:

enter image description here

Now, if you need something more global, IE: You want to affect all Views that contain your field and future views that will contain your field, then you need to use:

views-view-field--[field-name].html.twig

<div class="something">{{ output -}}</div>
0

There is a detailed answer in this Q: Overriding views-view-field.html.twig for specific fields. I'm not quite sure what the options for a content type are, but this is the answer for a template per fieldname: you can use views-view-field--fieldname.html.twig.

Of course, don't forget to clear your cache after creating the new template.

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.