2

I try to build a complete sentence based on tags as follows:

This is a sentence with tag1, tag2 and tag3.

My code is:

{% set topics = entry.topics.first %}

{% for topic in entry.topics.offset(1) %}
    {% if topic != entry.topics.last %}
       {% set topics = topics ~ ', ' ~ topic %}
    {% endif %}
{% endfor %}

<p>This is a sentence with {{ topics }} and {{ entry.topics.last }}.</p>

My problem is that the if clause does not work. The results is always:

This is a sentence with tag1, tag2, tag3 and tag3.

5

I think it'll be easier and more efficient to achieve that if you use the loop functionality instead of querying the actual tags. I think this code does what you want:

{% set topics = '' %}

{% for topic in entry.topics %}
    {% set topics = topics ~ topic ~ (loop.index < loop.length-1 ? ', ' : loop.index < loop.length ? ' and ') %}
{% endfor %}

<p>This is a sentence with {{ topics }}.</p>
| improve this answer | |
  • 1
    You can also use loop.last to trim that logic down even further. – Lindsey D Sep 14 '14 at 18:25

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.