I can't help but think this is a silly/obvious question, but I'm trying to retrieve the current section handle so I can use it as a class.

Maybe I'm going about it wrong, but {{ handle }} does nothing.

Any ideas?


One thing that’s important to remember is that there’s no inherent relationship between your templates and sections. Any template can show any entry from any section. So there’s no such thing as the “current section”.

If your section has the “Entries in this section have their own URLs” setting checked, and you’re requesting one of that section’s entries’ URLs, then the section’s template will get loaded automatically and an entry variable will be available to it, which represents the entry whose URL you requested. But that doesn’t mean that you couldn’t have loaded the same template some other way (e.g. via an {% include %} tag from another template), or that you couldn’t have manually fetched that entry some other way (e.g. with craft.entries).

Anyway, if you have an EntryModel variable set (such as that entry variable that you’d automatically get when accessing an entry’s URL), you can access it’s section using entry.getSection(), and you can access that section’s handle via its handle property.

{% set section = entry.getSection() %}
{% set handle = section.handle %}

That could be simplified to:

{% set handle = entry.getSection().handle %}

or even:

{% set handle = entry.section.handle %}
  • Nice, thank you! While this works for exactly what I need... I can see why this isn't always the best approach to assign each page with a generic class. The idea is just help with styling. I wonder (for future reference), how I might be able to get the same information via a plugin? Do you know of a PHP method? Thanks again :) Aug 8 '14 at 11:15
  • You can get the matched entry like so, and if there is one, you can access its section’s handle via $element->getSection()->handle. Aug 8 '14 at 12:35

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.