I have a pretty standard type entry page (_entry.html) which displays the details of an entry having navigated to it through 2 levels of categories. On this page I'd like to be able to query the two immediate category parents of this entry (sub-cat & cat) for use in a breadcrumb and page title variables.

I'm not sure how to approach this, or what the correct dot syntax is - I'm just getting up-to-speed with Craft CMS.

Any tips/references?

1 Answer 1


Assuming you have a Categories field associated with the entry, you can get all of the related categories in your template via entry.myCategoriesField (replace with the actual Categories field handle).

So here’s how you would loop through all of them:

{% for category in entry.myCategoriesField %}
    <li><a href="{{ category.url }}">{{ category.title }}</a></li>
{% endfor %}

If you just want the last 2 categories, you can use Twig’s slice filter:

normal syntax:
{% for category in entry.myCategoriesField|slice(-2) %}

shortcut syntax:
{% for category in entry.myCategoriesField[-2:] %}

If you want to set these categories to their own variables, so they can be referenced later on in your template, you could do this instead:

{% set parentCategory = entry.myCategoriesField.last() %}
{% set grandparentCategory = parentCategory.parent() %}
  • Aha, got it - I'm such a noob! Wasn't aware I could use negative syntax with 'Slice' either. Thx.
    – Britchie
    Commented Aug 16, 2016 at 19:54
  • One further question regarding this: I can see how I can employ this for use in a breadcrumb, but if I wanted to assign the category titles (there's 2 of them) to separate variables so I can use them elsewhere in my template, how would I go about this? I know I can use "entry.myCatField.first()" but stuck on how to query the parent. TIA
    – Britchie
    Commented Aug 16, 2016 at 22:16
  • @Britchie Lots of ways to do this but I just updated my answer with what I think would be the simplest/most readable one. Commented Aug 16, 2016 at 23:15
  • Those are really useful snippets and should solve my issue - thx so much for the follow-up Brandon.
    – Britchie
    Commented Aug 17, 2016 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.