rusttera

Built-in tester 'define' not working as I expected


I have a template with a section that should be rendered if a variable is defined. But I can't make it work. I have something like this in my project:

use serde::Serialize;

#[derive(Default,Serialize)]
struct AStruct {
  parameter: Option<String>
}

// AStruct { parameter: None }
let a_struct_instance = AStruct {..Default::default()};
TEMPLATES.render("template.conf", &a_struct_instance) {...}
// template.conf example:
//
// {% if parameter is defined %}
//   SOMETHING TO SHOW
// {% endif %}

The template is rendered like if parameter is defined, why is that?

The parameter field is None, but in the build-in tester function, 'value' is Some(Null) and is_some() return true on this.

https://github.com/Keats/tera/blob/master/src/builtins/testers.rs#L36

/// Returns true if `value` is defined. Otherwise, returns false.
pub fn defined(value: Option<Value>, params: Vec<Value>) -> Result<bool> {
    number_args_allowed("defined", 0, params.len())?;
    Ok(value.is_some())
}

What I'm doing wrong?


Solution

  • Well, my problem was that the testers 'is defined' or 'is undefined' checks if the variable is defined/undef, not the value of the variable.