HTML Auto-Escape
LiquidScript offers HTML auto-escaping. Where context variables are automatically escaped on output. Disabled by default, enable it by setting the Environment or Template.fromString() autoEscape
option to true
.
import { Environment } from "liquidscript";
const env = new Environment({ autoEscape: true });
const template = env.fromString("<p>Hello, {{ you }}</p>");
console.log(
template.renderSync({ you: '</p><script>alert("XSS!");</script>' })
);
output
<p>Hello, </p><script>alert("XSS!");</script></p>
Markup
Mark a string as "safe" by wrapping it in a Markup
object.
import { Environment, Markup } from "liquidscript";
const env = new Environment({ autoEscape: true });
const template = env.fromString("<p>Hello, {{ you }}</p>");
console.log(template.renderSync({ you: new Markup("<em>World!</em>") }));
<p>Hello, <em>World</em></p>
In general, if a filter manipulates a Markup
wrapped string in an "unsafe" way, the resulting string will be escaped on output.
toLiquidHtml
When HTML auto-escaping is enabled, if an object implements a toLiquidHtml
method, LiquidScript will use the string returned from [toLiquidHtml]()
instead of [toLiquidString]()
and toString()
on output.
import { Environment, Markup, toLiquidHtml } from "liquidscript";
class SomeObj {
toString() {
return "<em>World</em>";
}
}
class OtherObj {
[toLiquidHtml]() {
return "<em>World</em>";
}
}
const env = new Environment({ autoEscape: true });
const template = env.fromString("<p>Hello, {{ you }}</p>");
console.log(template.renderSync({ you: new SomeObj() }));
console.log(template.renderSync({ you: new OtherObj() }));
<p>Hello, <em>World</em></p>
<p>Hello, <em>World</em></p>