home ~ projects ~ socials

Convert a Text String to a Number in Rust's MiniJinja

This is a test to see about converting incoming text strings to integers that can be used in for loops in MiniJinja.

As of version 2.9.0, trying to convert something other than a number causes the page to fail to render.

I've opened a ticket about that here:

Converting to int halts rendering if the input is not a number

One possible work around is to create a function in the environment and use it to do the conversion. It can send back a none if the string can't be converted. That would allow a check to happen at the template level that wouldn't prevent the page from rendering.

---
[dependencies]
minijinja = { version = "2.9.0" }
---

use minijinja::{Environment, Value, context};

fn main() {
  let test_one = Value::from("1");
  let test_two = Value::from(2);
  let test_three = Value::from("a");
  do_output(&test_one);
  do_output(&test_two);
  do_output(&test_three);
}

fn do_output(input: &Value) {
    let mut env = Environment::new();
    env.add_template(
        "example", "{{ input|int }}"
    ).unwrap();
    if let Ok(template) = env.get_template("example") {
        match template.render(context!(input)) {
            Ok(output) => println!("{}", output),
            Err(e) => println!("{}", e)
        }
    }
}
Output:
1
2
invalid operation: invalid float literal (in example:1)
-- end of line --

References