Nikhil Tikoo
Nikhil Tikoo

Reputation: 375

Substring helper in handlebars

Can i write a helper in Handlebars that can tell if a string is a substring of another string?

I wrote the following code, but it doesn't seem to be working

This is the helper:

'if_sub': function(a, b, opts) {
     if (a.includes(b))
         return opts.fn(this);
     else
         return opts.inverse(this);
 }

And this is the implementation:

{{#if_sub colvalues "success"}}
    <td class="log-success"> {{colvalues}} </td>
{{/if_sub}}

Upvotes: 0

Views: 2302

Answers (1)

Mahi
Mahi

Reputation: 1727

just little mistake . if (a.includes(b)) should be if (b.includes(a))

<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>How to render html with Handlebars.js</title>
  <script src="https://cdn.jsdelivr.net/handlebarsjs/4.0.3/handlebars.min.js"></script>
  <script src="http://code.jquery.com/jquery-latest.min.js"    type="text/javascript"></script>
 
  <script id="simple-template" type="text/x-handlebars-template">

      {{#if_sub colvalues "success"}}
    <td class="log-success">  {{colvalues}} </td>
      {{/if_sub}}
  </script>
  
  <script type="text/javascript">
        Handlebars.registerHelper("if_sub",function(a, b, opts) {

     if (b.includes(a)){
       return opts.fn(this);
     }
         
     else{
       return opts.inverse(this);
     }
         
 });
  
    //wait for page to load
    $(document).ready(function(){
      var raw_template = $('#simple-template').html();
      var template = Handlebars.compile(raw_template);
      var data = {colvalues:"suc"}; //change value and see.
      var html = template(data);
      $('#main').append(html);

    });
  </script>
</head>
  
<body>
<!-- Insertion point for handlebars template -->
<div id="main" style="margin-left:100px">
</div>
</body> 
</html>

Upvotes: 1

Related Questions