Part of the EllisLab Network

Blog & News

Lisa Wess
Director of Community Services

Dissecting the Default Templates: Categories Variable Pair

Welcome to the Thursday installation of Dissecting the Default Templates.  Last week, we discussed custom weblog fields.

This week, we’re going to skip down a bit. The next few lines in our template include the simple use of some date variables and other variables which we have already discussed.

After that, however, we want to display what categories an entry belongs to, and so we’re going to discuss variable pairs, and specifically, the {categories} variable pair.

Onwards!

The next three lines that we’re going to discuss seem fairly simple:

{categories}
<a href="{path=site_index}">{category_name}</a> &#8226;
{/categories}

So, we have an entry and we have one or many categories assigned to that entry, and we wish to display that information on our template.  We can’t just throw in a variable for a category name because it has no context; it could be a custom field, for instance. In order to overcome this, we give it context in the template by using the {categories} variable pair; this way, ExpressionEngine knows that everything inside the {categories} and {/categories} tag pair is referencing variables within the context of the category.

We’ve seen a variable pair before in the article on Date Headings.  We know that a variable pair is used when we need to output data that, itself, has variables.  In this case, we want to output categories - but categories themselves have attributes such as a name, a URL title, a description, and category custom fields.  So, as mentioned before, we need the variable pair for context, and the variables themselves to output actual content.

Let’s begin by searching for categories.  Many results are returned, as categories are used throughout ExpressionEngine; however, we know that the correct link is the one referencing the Weblog Entries Tag as we are still working inside of that tag pair. Now, let’s click on the Weblog Entries Variable Pairs link and skip down to the categories section.

Because this is a variable pair, you can use some parameters to define how everything inside the pair will be limited and modified.  Then, any data you want displayed - for each category assigned to the entry being shown - will be placed inside the pair.

So, here we have a fairly simple concept that continues along with the ideas of giving context within templates, in order to pull out the appropriate data.  You can now take this information and use it on your own sites, to display what categories are appearing with any entry, and do so in any way that you wish for it to look.

Next week, we’re going to get a hint of conditionals, so stay tuned for that, it’ll be a blast!