Skip to content

Add filter to simplify handling of Option fields #424

@joshka

Description

@joshka

In a project I'm working on, CoPilot suggested some jinja syntax for handling an optional field (Option<i64>) as:

#[derive(Template)
struct Foo {
    bar: Option<i64>,
}
{{ bar | default(value="No bar", boolean=true) }}

Currently in askama this would require:

{% if let Some(bar) = bar %}
  {{ bar }}
{% else %}
  No bar
{% endif %}

The downside to using the name default here is that the jinja filter is about undefined or false variables, not Option variables. So the semantics are a little different between jinja and askama.

Jinja docs for default:
https://jinja.palletsprojects.com/en/stable/templates/#jinja-filters.default

jinja-filters.default(value: V, default_value: V = '', boolean: bool = False) → V

If the value is undefined it will return the passed default value, otherwise the value of the variable:

{{ my_variable|default('my_variable is not defined') }}

This will output the value of my_variable if the variable was defined, otherwise 'my_variable is not defined'. If you want to use default with variables that evaluate to false you have to set the second parameter to true:

{{ ''|default('the string was empty', true) }}

So I'd suggest either:

  1. accept that askama's syntax and features are oriented around Rust's semantics and so use default to interact with Option. I think this makes the most sense.
  2. bikeshed a different name rather than default to make it clear that the filter is different from jinja filter with the same name

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions