Optimizing "related posts" tera snippet

My posts have a “tags” taxonomy:

taxonomies = [{ name = "tags", feed = true }]

Which I set like this in my frontmatter:

[taxonomies]
tags = ["sysadmin","free-software","linux"]

Now, my related posts tera template looks like this:

{% set_global main_tag = "" %}
{% if page.taxonomies is containing("tags") %}
  {% for k, taxonomie in page.taxonomies %}
    {% if k == "tags" %}
      {% set_global tag_count = 0 %}
      {% for tag in taxonomie %}
        {% if tag_count == 0 %}
          {% set_global main_tag = tag %}
        {% endif %}
        {% set_global tag_count = tag_count + 1 %}
      {% endfor %}
    {% endif %}
  {% endfor %}
{% endif %}
{% if main_tag != "" %}
  {% set related_posts = get_taxonomy(kind="tags")
  | get(key="items")
  | filter(attribute="name", value=main_tag)
  | first
  | get(key="pages") %}
  {% set_global related_posts_counter = 0 %}
  {% if related_posts | length > 0 %}
    <section class="related-wrapper kg-width-full">
      <div class="container">
        <div class="kg-width-normal">
          <h3 class="related-title">You might also like</h3>
          <div class="related-feed">
            {% for post in related_posts %}
              {% if post.permalink != page.permalink and related_posts_counter <= 5 %}
                <article class="feed post">
                  <div class="feed-calendar">
                    {{ post.date | date(format="%b %d, %Y") }}
                  </div>
                  <h2 class="feed-title">
                    <a href="{{ post.permalink }}">{{ post.title }}</a>
                  </h2>
                  <div class="feed-right">
                    <div class="feed-length">
                      {{ post.reading_time }} min read
                    </div>
                  </div>
                  <svg class="icon feed-icon">
                    <use xlink:href="#chevron-right"></use>
                  </svg>
                </article>
                {% set_global related_posts_counter = related_posts_counter + 1 %}
              {% endif %}
            {% endfor %}
          </div>
        </div>
      </div>
    </section>
  {% endif %}
{% endif %}

It is inspired by this.

Ideally, I would like 5 posts that share any of the tags of the current post.

I don’t know how to do that, so right now this snippet is getting the “main tag” aka the first tag in the list of tags of the post, and they gets all posts matching this tag, and display up to 5 of them.

Problems:

  • This is very verbose and ugly
  • It is extremely slow :flushed: I have about 80 posts, without this snippet insert in each post, the site generates in ~700 ms, and with it in ~3s.

Is there any way to optimizee it?