1

I have some entries that have more than one category assigned to them (under the same category group). For example, Entry X might be assigned to Category A and Category D. How do I get it to print "Category A **and** Category B" instead of Category A Category B"?

3

Loop through the categories of the entry, add and if it's not the last loop index, like so:

{% for category in  entry.categoryFieldHandle %}
 {{category.title}} {{ loop.last ? '': 'and '}}
{% endfor %}
2

The accepted answer will work, certainly, but thanks to the way Craft works behind the scenes there is a more compact and elegant solution:

{{ entry.categoryFieldHandle|join(' and ') }}

Why this works

The Entry's category field (accessed via entry.categoryFieldHandle) returns an ElementCriteriaModel, which implements PHP's ArrayAccess interface.

In plain English, this means that we can treat the ElementCriteriaModel as an array.

The ElementCriteriaModel returns a collection of CategoryModel objects, each of which implements a __toString method (returning the Category title). This effectively means we can treat the object as a string.

The above features mean that we can pass our ElementCriteriaModel directly to the Twig join filter, and it will concatenate the Category titles using the "glue" string " and ".

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.