Creating a tag include

25 Jul 2023 4:19 PM    the blog jekyll
convert to local time zone


As I said in my post about tag pages, Jekyll allows you to have includes that accept parameters. In that post, I created an include for blog posts in a list. You may also remember that that article included examples of tags (such as the blog). The way that I did that was using another include, one that I created while writing that post and will explain in this post. After all, it’s much easier to say:

{% include tag.html name="the blog" %}

than

{% for tag in site.data.tags %}{%if tag.name == "the blog" %}{% assign css-class = "badge-info" %}{% if tag.class %}{% assign css-class = tag.class %}{% endif %}{% capture link %}/tags/{{ tag.name | replace: " ", "-" }}{% endcapture %}<a href="{{ link | relative_url }}" class="badge {{ css-class }}">{{ tag.name }}</a>{% endif %}{% endfor %}

This was mostly a straightforward process, so I won’t go into too much detail. I created _includes/tag.html with these contents:

{% for tag in site.data.tags %}{%if tag.name == include.name %}{% assign css-class = "badge-info" %}{% if tag.class %}{% assign css-class = tag.class %}{% endif %}{% capture link %}/tags/{{ tag.name | replace: " ", "-" }}{% endcapture %}<a href="{{ link | relative_url }}" class="badge {{ css-class }}">{{ tag.name }}</a>{% endif %}{% endfor %}

Note that I am expecting the include “parameter” to be name, as you can see since I compare tag.name to include.name.

Now that I had the include, I could replace every occurrence of this:

{% capture link %}/tags/{{ tag | replace: " ", "-" }}{% endcapture %}
<a href="{{ link | relative_url }}" class="badge {{ css-class }}">{{ tag }}</a>

with this:

{% include tag.html name=tag %}

This worked for _layouts/post.html and _includes/post.html, but blog.html looked like this:

{% capture link %}/tags/{{ tag[0] | replace: " ", "-" }}{% endcapture %}
<a href="{{ link | relative_url }}" class="badge {{ css-class }}">{{ tag[0] }}</a>

and saying {% include tag.html name=tag[0] %} caused errors, so I replaced it with this:

{% assign t = tag[0] %}
{% include tag.html name=t %}

There was one final problem, and that was spacing around the included tag. It would look something like this: (blah blah blah  the blog ). To fix this, I read this documentation page and changed the include to look like this:

{%- for tag in site.data.tags %}{%if tag.name == include.name %}{% assign css-class = "badge-info" %}{% if tag.class %}{% assign css-class = tag.class %}{% endif %}{% capture link %}/tags/{{ tag.name | replace: " ", "-" }}{% endcapture %}<a href="{{ link | relative_url }}" class="badge {{ css-class }}">{{ tag.name }}</a>{% endif %}{% endfor -%}

(note the {%- and -%} at the start and end), which fixed the issue.


Respond to this