2
votes

In Jekyll which uses the Liquid template language, I am on my blog page and I am displaying the latest 6 blog posts. For each post, I show the post date, name, excerpt, and the post url in a link.

I also want to be able to show the first tag of this post (for example, "Front-end development"). However, if there is more than 1 tag associated with the post, I want to display a fallback message saying "View tags", which toggles a dropdown with links to the other tags. If I can return an unordered list, that's fine, as I can take it from there.

This code doesn't work, but hopefully it illustrates what I'm trying to achieve:

{% for tag in post.tags %}
{% if tag.size > 1 %}
        <a class="toggle-tag-list">View tags</a>
        <ul class="tag-list hidden">
            <li><a href="{{ tag.url }}">tag 1</a></li>
            <li><a href="{{ tag.url }}">tag 2</a></li>
            <li><a href="{{ tag.url }}">tag 3</a></li>
        </ul>
    {% else %}
    <a href="{{ tag.url }}">{{ tag }}</a>
{% endif %}
{% endfor %}
1

1 Answers

2
votes

Edited answer :

I saw that tag.url returns nothing and it's normal. But, if you are using tag pages (by hand or with jekyll-paginate-v2), you already know their urls. You can craft something like I'm doing in this edit for href supposing that your tag pages urls are of the form /site.basurl/tag/tagname/.

Feel free to adapt the code.

You can try this :

{% if post.tags.size > 0 %}
  {% if post.tags.size > 1 %}
    <a class="toggle-tag-list">View tags</a>
    <ul class="tag-list hidden">
      {% for tag in post.tags %}
        <li><a href="{{ site.baseurl }}/tag/{{ tag | slugify: "ascii" }}/">{{ tag }}</a></li>
      {% endfor %}
    </ul>
  {% else %}
    <a href="{{ site.baseurl }}/tag/{{ post.tags.first | slugify: "ascii" }}/">{{ post.tags.first }}</a>
  {% endif %}
{% endif %}