Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter Taxonomies using Rust-based Zola / Tera?

I have recently discovered Zola and Tera (Rust frameworks for statically-generated websites) and found them amazing.

I'm trying to filter specific category pages to display in a section on the same page. To illustrate, I wrote some code like this:

<div class="content">
    {% block content %}
    <div class="list-posts">
        {% for page in section.pages %}
        {% for key, taxonomy in page.taxonomies %}
        {% if key == "categories" %}
        {% set categories = taxonomy %}
        {% for category in categories %}
        {% if category == "rust" %}
        <article>
            <h3 class="post__title"><a href="{{ page.permalink }}">{{ page.title }}</a></h3>
        </article>
        {% endif %}
        {% endfor %}
        {% endif %}
        {% endfor %}
        {% endfor %}
    </div>
    {% endblock content %}
</div>

There should be MULTIPLE sections of the code above for different categories, e.g. "rust", "java", etc.

I wrote the code to explain my question, but it isn't the way I want it (and it doesn't work when the sections are duplicated).

How do I do the filtering of the particular category when the sections/pages are loaded?

The front-matter metadata in the content file is:

title = "A web page title"
[taxonomies]
categories = ["rust"]

If you see my example code above, I have to access it first via a hash map, then an array, in order to filter all pages which is "rust".

The filter below doesn't work:

for page in section.pages | filter(attribute="taxonomies.categories", value="rust"
like image 930
ikevin8me Avatar asked Sep 25 '18 02:09

ikevin8me


1 Answers

I managed to resolve it. First, I did tests like this:

HTML test print output
{% set categories = get_taxonomy(kind="categories") %}
{% set rustItems = categories.items | filter(attribute="name", value="rust") %}
{% set javaItems = categories.items | filter(attribute="name", value="java") %}
{{ rustItems[0].pages | length }}
<br>
{{ rustItems[0].pages[0].title }}
<br>
{{ rustItems[0].pages[1].title }}
<br>

I was able to pick up the title as set in the .md file.

So I moved on further and I did:

{% set categories = get_taxonomy(kind="categories") %}
{% set category = categories.items | filter(attribute="name", value="business") | first %}
{% for page in category.pages %}
{{ page.title }}
... etc.

The above code will filter the pages for category taxonomy.

like image 128
ikevin8me Avatar answered Nov 05 '22 05:11

ikevin8me