3

I am trying to implement a carousel , inside my views-view-fields--block_1.html.twig , I want to add active class inside the div for the first Iteration . I have added the code in twig file but every time it is adding active class for all the iteration.

code snippet:

{% if fields.counter.content == 1 %}
{% set tag = "active" %}
{% else %}
{% set tag = "" %}
{% endif %}

In my view title,body,image and result counter fields are there . From result counter i am getting the value and comparing inside the above twig file. Can anyone give suggestion, how to achieve this.

Thanks,

3
  • This is weird, if anything, your problem should be the other way around, where the tag is always empty. How can the counter be 1 for all rows? Try doing a {{ fields.counter.content }} and see what number shows up.
    – No Sssweat
    Dec 3, 2017 at 6:58
  • Did you try quoting the 1? So fields.counter.content == "1" - I could imagine that the field content renders to a string value and your unquoted condition evaluates to true as it checks whether the content is set. (Can't fiddle on a template right now, as I'm not in my office.) Dec 3, 2017 at 15:56
  • Thanks giving for suggestions , fields.counter.content == "1" worked for me.
    – Debasish
    Dec 4, 2017 at 6:32

1 Answer 1

1

If your code snippet is within a for loop, you could use either loop.first or loop.index in your if statement to target the first iteration. Refer to https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable

Thus your twig template would probably resemble:

{% for item in items %}
  {% if loop.first 1 %}
    {% set tag = "active" %}
  {% else %}
    {% set tag = "" %}
  {% endif %}

... render row/field with class in template ...
{% endfor %}

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.