Handlebars.js – How to escape or display special html characters

Handlebars by default escapes special characters.

So, if you trying to print special characters like or ® etc, they will be escaped and the corresponding html codes will be printed.

For example ,

<!DOCTYPE html>
<html>
<head>
<title>Handlebars js</title>
<script type="text/javascript" src="handlebars-v4.0.10.js"></script>
</head>
<body>

  <div id="displayArea"></div>

  <script id="myTemplate" type="text/x-handlebars-template">
    <h1>{{desc}}</h1>
</script>

  <script type="text/javascript">
    var tmpHtml = document.getElementById("myTemplate").innerHTML;
    var template = Handlebars.compile(tmpHtml);
    var data = template({
      desc : "TopJavaTutorial&trade;"
    });

    document.getElementById("displayArea").innerHTML += data;
  </script>

</body>
</html>

Output :

handlebars escape html

Note that, the above example doesnot print the ™ symbol. Rather, it prints the html characters as is.

However, if you don’t want Handlebars to escape a value, use the “triple-stash”, {{{

For example :

<h1>{{{desc}}}</h1>

Here is the complete code :

<!DOCTYPE html>
<html>
<head>
<title>Handlebars js</title>
<script type="text/javascript" src="handlebars-v4.0.10.js"></script>
</head>
<body>

  <div id="displayArea"></div>

  <script id="myTemplate" type="text/x-handlebars-template">
    <h1>{{{desc}}}</h1>
</script>

  <script type="text/javascript">
    var tmpHtml = document.getElementById("myTemplate").innerHTML;
    var template = Handlebars.compile(tmpHtml);
    var data = template({
      desc : "TopJavaTutorial&trade;"
    });

    document.getElementById("displayArea").innerHTML += data;
  </script>

</body>
</html>

This will print the ™ symbol as shown below.

handlebars unescape html

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags