Need some help in using macros


#1

I’m using Zola with Tera and I have repeating code within the HTML. I’m trying to put it into macros but can’t figure it out. Please help! :slight_smile:

The code is:

{% set section = get_section(path="Section_A/_index.md") %}
    {% set sectionsPagesCount = section.pages | length %}
    {% set_global sectionsPhotosCount = 0 %}
    {% for page in section.pages %}
      {% set pagePhotosCount = page.assets | length %}
      {% set_global sectionsPhotosCount = sectionsPhotosCount + pagePhotosCount %}
    {% endfor %}

    <div class="col-lg-3 col-md-6 mb-lg-0 mb-4">
      <div class="card card-cascade narrower card-ecommerce">
        {% include "section_image.html" %}
        {% include "section_info.html" %}
      </div>
    </div>

    {% set section = get_section(path="Section_B/_index.md") %}
    {% set sectionsPagesCount = section.pages | length %}
    {% set_global sectionsPhotosCount = 0 %}
    {% for page in section.pages %}
    {% set pagePhotosCount = page.assets | length %}
    {% set_global sectionsPhotosCount = sectionsPhotosCount + pagePhotosCount %}
    {% endfor %}

    <div class="col-lg-3 col-md-6 mb-lg-0 mb-4">
      <div class="card card-cascade wider card-ecommerce">
        {% include "section_info.html" %}
        {% include "section_image.html" %}
      </div>
    </div>

    {% set section = get_section(path="Section_B/_index.md") %}
    {% set sectionsPagesCount = section.pages | length %}
    {% set_global sectionsPhotosCount = 0 %}
    {% for page in section.pages %}
    {% set pagePhotosCount = page.assets | length %}
    {% set_global sectionsPhotosCount = sectionsPhotosCount + pagePhotosCount %}
    {% endfor %}

    <div class="col-lg-3 col-md-6 mb-lg-0 mb-4">
      <div class="card card-cascade narrower card-ecommerce">
        {% include "section_image.html" %}
        {% include "section_info.html" %}
      </div>
    </div>

… and so on.

As you can see, only the first line line “set section = …” is unique. The rest of the lines until the {% endfor %} are the same.

How do I use macros?

(I also tried to use include, but it didn’t work.)

Thanks!


#2

Hi, have you tried reading Tera’s docs about macros? Tera is the templating engine used by Zola so in case you have troubles with Zola templates you should go take a look in Zola’s docs.

If the examples in the docs are not clear feel free to ask more questions :slightly_smiling_face:
Good luck working on your macros!