Keats / tera

A template engine for Rust based on Jinja2/Django
http://keats.github.io/tera/
MIT License
3.54k stars 283 forks source link

Dynamicaly add a key/value to a map #673

Open pcoves opened 3 years ago

pcoves commented 3 years ago

Hi there.

First of all, thanks for the excellent work here!

I'm looking for a way to dynamically add a key/value to a map. I tried everything that came to my mind with no success so here I am.

For the context, I'm using tera through zola and I'm building a galery page. I have N co-located assets with a naming convention : image.ext.toml and every toml contains the title and the alt of the image.ext file.

I can load the toml files using load_data and get a map which is nice. Because of reasons, I'd like to add "path": "image.ext" to the map and have this in the end:

{
    "path": "image.ext",
    "title": "Image title",
    "alt": "Image alt"
}

Is this possible at the moment? I was hoping for something like the concat function but it only works for arrays as far as I know.

Many thanks in advance!

P.

Keats commented 3 years ago

It's not possible currently

pcoves commented 3 years ago

Would it be something worth spending some time on?

If yes, I'd gladly look into it and submit a PR in case of success.

Keats commented 3 years ago

It would be nice, I'm just not sure what the syntax should be

pcoves commented 3 years ago

I did not dive into the code yet but I'm thinking of a filter like map | insert(key="foo", value="value") returning a new map.

Keats commented 3 years ago

So it would have to be used with a set right?

pcoves commented 3 years ago

Either set or set_global yes.

Something like:

{% set data = load_data(path="file.toml") %}
{% set data = data | insert(key="key", value="value") %}

Or even

{% set data = load_data(path="file.toml") | insert(key="key", value="value") %}