Handlebars HTML-escapes values returned by a
{{expression}}
. If you don't want Handlebars to escape a value, use the "triple-stash",{{{
What does it mean to HTML-escape a value?
The following characters are reserved in HTML and must be replaced with their corresponding HTML entities: ~(Online HTML Formatter)
"
is replaced with "
&
is replaced with &
<
is replaced with <
>
is replaced with >
Examples say more than a thousand words:
var source = $("#template").html();
var template = Handlebars.compile(source);
var data = {
escaped : '{{}}',
notescaped: '{{{}}}',
html : "<a href='https://google.com/'>Google <strong>Search</strong></a>",
}
$('body').append(template(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script id="template" type="text/x-handlebars-template">
<h4>Escaped HTML double curly brackets: <code>{{escaped}}</code></h4>
{{html}}
<p>It's just non interactive string</p>
<hr>
<h4>Not escaped HTML tripple curly brackets: <code>{{notescaped}}</code></h4>
{{{html}}}
<p>It basically ends up as parsed HTML</p>
</script>
And then, handlebarsjs.com on the matter is a good read, too.
If you have a string like <br>
in your expression, using two brackets ({{ expression }}
) would convert that <br>
into an HTML break element.
But if you use three brackets ({{{ expression }}}
), then the <br>
would print how it appears and would not be converted into an HTML element.
From their documentation:
If you look at the h1
tag, the <p>
tag is escaped and so its displayed as <p>
;
If you look at the body
tag, because of {{{}}}
the string is displayed however it is. the first <p>
tag and last </p>
closing tags are not escaped.
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{{body}}}
</div>
</div>
and the values of title and body are as follows
{
title: "All about <p> Tags",
body: "<p>This is a post about <p> tags</p>"
}
The resulting is:
<div class="entry">
<h1>All About <p> Tags</h1>
<div class="body">
<p>This is a post about <p> tags</p>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With