Capture classes in Liquid to add to element
When using Liquid files for html templates you might want to add classes based on something, how many items there are or what settings are used.
I have some basic classes I set on the body tag. For example I want to know if current collection type or post type is rendered. Is it and index page or a single page?
So the end result is something like this:
<body class="page is-index has-accent is-homepage has-devmode">
...
<main>...</main>
</body>
So this list of classes is added to the class attribute:
- page
- is-index
- has-accent
- is-homepage
- has-devmode
- size-[x] e.g. size-3
The most elegant way to do this in Liquid is as follows:
{%- capture bodyClasses -%}
{{ post.content_type.name }}
{% if post.is_index == true %}is-index{% endif %}
{% if post.highlight == true %}has-accent{% endif %}
{% if post.is_homepage %}is-homepage{% endif %}
{% if site.dev_mode %}has-devmode{% endif %}
{{ site.collection.size | prepend: "size-" }}
{%- endcapture -%}
<body id="body"
class="{{ bodyClasses | strip_newlines }}">
By using strip_newlines
we remove the newlines that are added by the capture tag. This way we can add the classes in a readable way in the capture tag.
That way the string of classes is not bulky and does not use multiple lines. It is easy to read and maintain.
The capture tag is a great way to add classes to the body tag or any other element in your Liquid theme.
- Next: Use contains in if statement in Liquid
- Previous: Upping my javascript game