← back to the index


Using Handlebars on both the server and client side

Posted in Technology

After some digging around the bowels of StackOverflow threads -- most people mentioning I should be using another template processing language on my NodeJS application (Jade or Swig) seemed to be mentioned otfen.

But fancy that, I wanted to use only one templating language for the entireity of my application -- both front and back. I mean its 2015 right?

Its turns out the answer is rather simple -- you just need to escape the handlebars on the server side and thats enough for them not to be processed until they are on the client side. Its not the most elegant solution and I am sure I could write a helper application to wrap and protect my templates but that was less than ideal because then my IDE would mess up code coloring.

So in my server side application, a snippet which looked like this..

<script id="slide-template" type="text/x-handlebars-template">

  <div id="slick-slider">

  {{#each slides}}

    <div><img src="{{media}}"><h3>{{caption}}</h3></div>

  {{/each}}

  </div>

</script> 

was just turned into this...

<script id="slide-template" type="text/x-handlebars-template">

  <div id="slick-slider">

  \{{#each slides}}

    <div><img src="\{{media}}"><h3><!-- {{caption}} --></h3></div>

  \{{/each}}

  </div>

</script>