Including javascript within mustache template

javascript, mustache

Solution

Your json-input should reference the script to call:

JSON

 var json = {
   id: "someid",
   gaFillSlot: function(){
     GA_googleFillSlot("MPU");
   }
 }

TEMPLATE

 <script id="mustache-post-advert" type="text/mustache">
   <article id="post-{{id}}" class="post">
     {{gaFillSlot}}
   </article>
 </script>

Make sure 'GA_googleFillSlot' is available to be called from the context of mustache at time of templating.

This is in line with the logic-less nature of Mustache: any logic you want should be embedded into the json you pass to Mustache to bgin with.

Didn't test this, but this should work. HTH

Problem

I have a block of javascript for displaying adverts that I wish to include every nth time on a page. I'm using Mustache as my templating language but cannot work out how to include the js so it runs as a script rather than just being inserted as a string. ``` <script id="mustache-post-advert" type="text/mustache"> <article id="post-{{id}}" class="post"> {{{ <script type="text/javascript">GA_googleFillSlot("MPU")</script> }}} </article> </script> ``` I've tried triple { which I hoped would escape but sadly it didn't.

Original source