Handlebars.js – Unless helper

handlebars unless helper logo
The unless helper in handlebars works as “if not”.

So, the block under the unless helper will be rendered if the expression passed is false.

For example, the following code will display the block of text “No name element present” only if name is not available in the context.

{{#unless name}}
  <h1>No name element present</h1>
{{/unless}}  

Here is the complete 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">
   {{#unless name}}
    <h1>No name element present</h1>
   {{/unless}}  
</script>

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

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

</body>
</html>

In the above data passed, “name” element is not there. Therefore the message will be displayed.
 

Output :

handlebars unless helper
 

© 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