Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Liquid: length of string, size of vector

  • len

  • size

  • Sometimes we would like to display or compare the length of a string or the number of elements in a vector.

  • We can do that using the size attribute.

fn main() {
    let text = "Some text";
    let animals = vec!["cat", "dog", "snake"];
    println!("{}", text.len());
    println!("{}", animals.len());
    assert_eq!(text.len(), 9);
    assert_eq!(animals.len(), 3);

    let template = "text: {{ text.size }} animals: {{ animals.size }}. The string is {% if text.size > 10 %}long{% else %}short{% endif %}.";

    let template = liquid::ParserBuilder::with_stdlib()
        .build()
        .unwrap()
        .parse(template)
        .unwrap();

    let globals = liquid::object!({
        "text": text,
        "animals": animals,
    });
    let output = template.render(&globals).unwrap();

    println!("{}", output);
    assert_eq!(output, "text: 9 animals: 3. The string is short.");
}
9
3
text: 9 animals: 3. The string is short.