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.


examples/liquid/embed-html-tags/src/main.rs
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>");
}

examples/liquid/embed-html-tags/out.txt
<h1>Welcome to Liquid</h1>
<h1>Welcome to <></h1>
<h1>Welcome to &lt;&gt;</h1>