mitsuhiko / minijinja

MiniJinja is a powerful but minimal dependency template engine for Rust compatible with Jinja/Jinja2
https://docs.rs/minijinja/
Apache License 2.0
1.56k stars 86 forks source link

How to set the default value for Option<String>variable when it is empty #536

Closed sunkaifei closed 1 month ago

sunkaifei commented 2 months ago

How to set the default value for Optionvariable when it is empty For example, when my content: Optionis empty, the template displays' none '. My GPT asked me to write' {{content | default ('Default Value')}} 'in this way, but it still doesn't work and displays' none'

sunkaifei commented 1 month ago

The current temporary solution is

{% if field.name %}{{ field.name }}{% endif %}

@mitsuhiko Is it better to have a built-in processing method? For example:


{{ field.name | default("no") }}
mitsuhiko commented 1 month ago

That is intentional. A field that is set to None is treated like a field set to (). One solution would be to register a custom |default filter that sets it to an empty string or else (see also discussion in #444).

There is an example that shows how this can be done: https://github.com/mitsuhiko/minijinja/blob/main/examples/none-as-undefined/src/main.rs

sunkaifei commented 1 month ago

This custom tag is very practical and excellent!