DEV Community

loading...

How to split a string in Handlebars template

rossellafer profile image Rossella Ferrandino ・2 min read

Sometimes Shopify themes will use Handlebars for components like the Shopify predictive search or the ajax cart. Handlebars compiles templates into JavaScript functions, and makes the template execution faster.

So for example you could see in a theme a snippet called predictive-template.liquid, which loops through the products returned by the search and outputs html including their title, price, an image etc.

This is what a Handlebars template will look like - I got this from a paid Shopify theme I was adding custom functionality to today:

<div>
    {% raw %}
      {{#if products}}
        <div data-type-products>
          <div class="grid grid--uniform">
            {{#products}} 
          <div class="grid-product__meta">
            <div">{{title}}</div>
          </div>
          {{#if image }}
           <img class="image-fit lazyload"
             data-src="{{image}}"
             data-widths="[180, 360, 540, 720]"
             data-sizes="auto">
          {{/if}}
         </div>
     </div>
{% endraw %}
</div>
Enter fullscreen mode Exit fullscreen mode

Variables like title or image are returned from the get request to the endpoint search/suggest.json, which is made in a JavaScript file like theme.js.

What I wanted to do today was manipulate the product title string to remove the first 10 letters. In order to do that in Handlebars, I created a helper, which I then added to the JavaScript file that was handling the template compilation. The documentation on how to use registerHelper in Handlebars is here
This is my code:

Handlebars.registerHelper('sliceTitle', function(passedString) {
  var theString = passedString.substring(10,100);
    return new Handlebars.SafeString(theString)
});
Enter fullscreen mode Exit fullscreen mode

Handlebars.SafeString(string) is a built in helper that prevents string from being escaped when the template is rendered.
Finally, I modified the Handlebars template to use the helper just created.

<div class="grid-product__meta">
  <div">{{sliceTitle title}}</div>
</div>
Enter fullscreen mode Exit fullscreen mode

And that's it, this is how I created my custom Handlebars helper to manipulate the results returned from the predictive search and outputted using a Handlebars template.

Discussion

pic
Editor guide