Sometimes it’s useful to iterate over files to use them in templates. You can do this using page.assets
, but this does not include files that are not colocated with that page.
We could have a get_files(path=<some path>)
that returns a list of files in path
. Optionally we could make that recursive.
Additionally, it would be useful for get_files
to accept some glob, for example get_files(path=<some_path>, glob="*.jpg")
, because otherwise looping over the returned vector might be a big cumbersome.
With the glob
, if you want to iterate over images in static/mypost
you could just do:
{% for asset in get_files(path=static/page.slug, glob="*.jpg") %}
{% if loop.index is odd %}<div class="row">{% endif %}
<div class="column">
<a class="gallery-item" href="{{ get_url(path=asset) }}" >
<img src="{{ get_url(path=asset) }}">
</a>
</div>
{% if loop.index is even or loop.last %}</div>{% endif %}
{% endfor %}
Otherwise you would need to filter the elements inside a loop, which messes with the loop.*
variables, which are sometimes useful for templating, you would have to write something like:
{% set_global idx = 0 %}
{% for asset in page.assets %}
{% if asset is matching("[.](jpg)$") %}
{% set_global idx = idx + 1 %}
{% if idx is odd %}<div class="row">{% endif %}
<div class="column">
<a class="gallery-item" href="{{ get_url(path=asset) }}" >
<img src="{{ get_url(path=asset) }}">
</a>
</div>
{% if idx is even or loop.last %}</div>{% endif %}
{% endif %}
{% endfor %}
What do you think?