14

I'm setting my categories by matching the third segment to a category slug. How do I get the category title?

{% set catSlug = craft.request.getSegment(3) %}
{% set category = craft.categories.slug(catSlug) %}

{{ category.slug }} returns the slug, but {{ category.title }} returns nothing.

2
  • If {{ category.slug }} is giving you the slug, it sounds like you’ve got is actually working. Not sure why {{ category.title }} would not be working though. What does {{ dump(category) }} give you? (you’ll need to have dev mode enabled to use that dump() function.) Commented Jul 30, 2014 at 11:39
  • Hmm looks right to me? Could be the category is disabled? Commented Jul 30, 2014 at 12:14

1 Answer 1

24

You need to add .first() when setting the category. As far as I can tell, if you don't have .first() only {{ category.slug }} will work.

First get the slug:

{% set catSlug = craft.request.getSegment(3) %}

This will give you the CategoryModel object for catSlug:

{% set category = craft.categories.slug(catSlug).first() %}

You can now access whatever you want from the category, like the title:

{{ category.title }}
5
  • 1
    You can’t pass in a string (catSlug) to craft.categories() – that .slug( is required to tell Craft that what you’re passing in is the slug, as opposed to an ID, etc. Commented Jul 30, 2014 at 11:36
  • @Brandon Required as in it won't work without it or as in you really should use it? This code worked for me, maybe my test wasn't in a clean enough environment. Commented Jul 30, 2014 at 18:36
  • 1
    Required as in there’s no way it will work that way, and if it appeared to work, you probably just got lucky with the desired category happening to be the first one in the group. Commented Jul 30, 2014 at 22:08
  • @Brandon You got it, I did get lucky. :) I edited my answer, the lack of .first() is what was giving @brunam problems. Commented Jul 30, 2014 at 23:01
  • 1
    Ah good catch! That explains why category.slug was working but category.title wasn’t – it was just returning the parameter value, rather than an actual category’s slug. Commented Jul 30, 2014 at 23:45

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.