Displaying the Current “Section” Name
Problem
You want to display the current “section” name in your template.
Solution
Sections don’t have their own templates in Craft in the way that entries can, so the solution depends on the page in question.
As an example, let’s assume you’re building a directory of hotels—stored in a section with a handle of hotels
, and a name of “Salubrious Accommodations”—and three pages:
- A list of all the hotels, available at
/hotels
. - Details for an individual hotel, available at
/hotels/{my-hotel-slug}
. - A list of all the hotels in a given city, available at
/cities/{city-slug}/hotels
.
On each of these three pages you want to display the hotels
section name in your template (say, in the title
tag), but you don’t want to hard-code it, in case the site owner decides to go with a less flowery title in the future.
The hotels list page
In order to retrieve a list of hotels to display, your template will contain some code similar to this:
{% set entries = craft.entries.section('hotels') %}
That is, you will have hard-coded the section handle, in order to retrieve the associated entries.
You can retrieve the section details using the same handle, and then output the section name, as follows:
{% set section = craft.sections.getSectionByHandle('hotels') %}
<title>{{ section.name }}</title>
The hotel details page
On the hotel details page, Craft automatically provides you with an entry
variable. Use that to access the section name, like this:
<title>{{ entry.section.name }}</title>
The “city hotels” list page
You have two options for the “city hotels list page.
The standard “hotels list” technique will work just fine here too, or you can dynamically retrieve the section handle from the appropriate URL segment.
<title>{{ craft.sections.getSectionByHandle(craft.request.segments[2]).name }}</title>
This alternative approach will actually work with any page where the section handle appears in the URL, including the previous two scenarios.
Submitted by Stephen Lewis on 1st February, 2017