Keats / tera

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

More ergonomic way of access [object] fields? #841

Closed maxdymond closed 1 year ago

maxdymond commented 1 year ago

Hi,

I added a custom function yamlload which loads a Yaml file into a Value using serde_yaml. I was wondering the most ergonomic way of accessing the fields within it.

At the moment I think I'm limited to code like:

{{ yamlload(file="random.yml") | get(key="variables") | get(key="foo") }}

for filename "random.yml"

variables:
  foo: bar

as I tried the get(key="variables/foo") syntax from the docs but that didn't appear to work. I also tried {{ yamlload(file="random.yml").variables.foo }} but that didn't work either.

Is there a more ergonomic syntax here?

Keats commented 1 year ago
{% set data = yamlload(file="random.yml") %}
{{ data.variables.foo }}

should work?

maxdymond commented 1 year ago
{% set data = yamlload(file="random.yml") %}
{{ data.variables.foo }}

should work?

I don't think it does because the docs say:

Currently functions can be called in two places in templates:

variable block: {{ url_for(name="home") }}
for loop container: {% for i in range(end=5) %}

Trying it I get:

Error { kind: Msg(" --> 1:43
  |
1 | {% set data = yamlload(file=\"random.yml\") }
  |                                           ^---
  |
  = expected `or`, `and`, `not`, `<=`, `>=`, `<`, `>`, `==`, `!=`, `+`, `-`, `*`, `/`, `%`, a filter, or `%}` or `-%}`"), source: None })
Keats commented 1 year ago

The docs are outdated, you can definitely call it as a set, eg https://github.com/getzola/zola/blob/master/docs/templates/shortcodes/gallery.html#L4 in the Zola docs

In your snippet, you are missing the % in the closing brace

maxdymond commented 1 year ago

Ah yes, stupid typo. Works great, thankyou!