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: Embed HTML - escape HTML

By default liquid inserts values as they are.

This means if a value we use in a template contains any HTML special character, that will be included in the resulting HTML. This can break the HTML and can open your site to HTML injection attack.

We can use the escape filter on each field where we would like to avoid this.

fn main() {
    plain_text();
    embed_html();
    escape_html();
}

fn plain_text() {
    let template = liquid::ParserBuilder::with_stdlib()
        .build()
        .unwrap()
        .parse("<h1>Welcome to {{field}}</h1>")
        .unwrap();

    let globals = liquid::object!({
        "field": "Liquid"
    });
    let output = template.render(&globals).unwrap();
    println!("{}", output);
    assert_eq!(output, "<h1>Welcome to Liquid</h1>");
}

fn embed_html() {
    let template = liquid::ParserBuilder::with_stdlib()
        .build()
        .unwrap()
        .parse("<h1>Welcome to {{field}}</h1>")
        .unwrap();

    let globals = liquid::object!({
        "field": "<>"
    });
    let output = template.render(&globals).unwrap();
    println!("{}", output);
    assert_eq!(output, "<h1>Welcome to <></h1>");
}

fn escape_html() {
    let template = liquid::ParserBuilder::with_stdlib()
        .build()
        .unwrap()
        .parse("<h1>Welcome to {{field | escape}}</h1>")
        .unwrap();

    let globals = liquid::object!({
        "field": "<>"
    });
    let output = template.render(&globals).unwrap();
    println!("{}", output);
    assert_eq!(output, "<h1>Welcome to &lt;&gt;</h1>");
}
<h1>Welcome to Liquid</h1>
<h1>Welcome to <></h1>
<h1>Welcome to &lt;&gt;</h1>