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 %}
$element->getSection()->handle
.
Commented
Aug 8, 2014 at 12:35