Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including javascript within mustache template

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.

like image 611
BobFlemming Avatar asked Jul 03 '12 15:07

BobFlemming


People also ask

How does mustache JS work?

It works by expanding tags in a template using values provided in a hash or object. We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values.

How handlebars JS is different from mustache JS?

Handlebars. js is an extension to the Mustache templating language created by Chris Wanstrath. Handlebars. js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be; Mustache: Logic-less templates.

How do I render a mustache in HTML?

render = function (template, view, partials) { return this. compile(template)(view, partials); }; This is the most basic form of templating with mustache. Let's see the other methods available for creating more organized code.


1 Answers

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

like image 104
Geert-Jan Avatar answered Oct 13 '22 22:10

Geert-Jan