How to use taxonomy terms to help style content in Statamic
If you're coming from WordPress, you might be used to using taxonomies and template names to style content. Here's how to replicate that in Statamic.
A user in the Statamic Discord, Mayo, asked:
Is there a way to get taxonomy/tags added as an html attribute, or class? So i can style individual items based on their taxonomy/tag. I can’t find anything in the docs that alludes to this. Is it possible without building an addon?
The short answer is yes.
Let’s say you have a blog about cars, built on Statamic. You want to be able to provide a nod to the brand of the car being written about in the blog post. For example, you’re writing about a new Ford car and you want to pass through the Ford blue to the top border of the article.
We might have a CSS class called brand-ford
, with the following properties and values:
.brand-ford {
border-top: 4px solid #1351d8;
}
Let’s say you have a taxonomy called Brand set up, and Ford is one of the terms in it. You would select this brand when you’re writing the review.
You could want your review section to look like:
<article class="review brand-ford">
<h2>Your review title</h2>
// Your review goes here.
</article>
So how do you dynamically call that in?
<article class="review brand-{{ brand }}{{ slug }}{{ /brand }}">
<h2>{{ title }}</h2>
{{ content }}
</article>
What’s happening here? Well, the {{ brand }}
tag is telling Statamic you want to access the array called brand, which is the taxonomy that is associated with the post. You’re then telling Statamic you want to return the slug associated with the term in the brand array.
In this case, it would return ford
.
Why do we want {{ slug }}
in this case? Well, we’re using it to access a class name, which is lower case, so we want it lower case. We could use the lower
modifier to return Ford
as ford
, but we also know there are some brands that have two or three words in their name. By calling the slug, it will automatically be returned as lowercase, and kebab case; e.g. alfa-romeo
or land-rover
.
An even simpler way*
*assuming you will only ever have one term associated with an taxonomy, that is.
Let’s say you know you’re only ever going to associate one term per taxonomy. I.e. it’s unlikely a car would have two manufacturers. So you could easily set the taxonomy to only allow one term.
In that case, the value of brand
in Statamic wouldn’t be an array, but would be a string; e.g. Ford. That way, you’d be able to achieve the same as the above by just doing:
<article class="review brand-{{ brand }}">
<h2>{{ title }}</h2>
{{ content }}
</article>
If you want to add it to the HTML tag (which I’d recommend against, but as Mayo asked), you’d simply open your layout file, and add it to the file like so:
<!DOCTYPE html>
<html class="brand-{{ brand }}">
<head>
...
This would return:
<!DOCTYPE html>
<html class="brand-ford">
<head>
...