Description
The Tera manual says this about the filters first
, last
and nth
:
If the array is empty, returns empty string.
The Jinja 2.11.x template designer documentation doesn't seem to specify what happens for an empty sequence in first
and last
, but according to the following experiment in Python, it's undefined and not an empty string. Undefined does make more sense in some cases and is more general:
from jinja2 import Template
template = Template("hello, ?{{ items | first | default('world') }}?")
output = template.render(items=[])
print(output)
This prints hello, ?world?
. The same in Tera 1.3.1 would be
let input = "hello, ?{{ items | first | default(value='world') }}?";
let mut context = Context::new();
context.insert("items", &Vec::<&str>::new());
let output = Tera::one_off(input, &context, false).unwrap();
println!("{}", output);
which prints hello, ??
as expected because the value from first
is defined, so default
does not trigger.
Printing the value from first
for an empty sequence is still well defined in Jinja2. From the template designer docs (this seems to already happen in Tera as well for undefined values, such as printing items[1] for empty items):
If a variable or attribute does not exist, you will get back an undefined value. What you can do with that kind of value depends on the application configuration: the default behavior is to evaluate to an empty string if printed or iterated over, and to fail for every other operation.
Consider changing the behaviour of these three filters to prefer undefined (null) over empty string.