Search code examples
javascripttemplatesmustachemustache.php

Reuse mustache.php in mustache.js


I recently started to use Mustache and I'm in a position where I need to reuse PHP templates also in JS. Although I compiled templates into JS, sometimes is more convenient to just embed templates like this

<script type="text/template" id="my-tpl">
  {{foo}}
</script><!-- /#my-tpl -->

(and then use from JS).

The problem starts now: since I'm displaying this from Mustache.php, the {{foo}} variable is parsed, therefore is not available from JS anymore. The only solution I found is to use different template tags (e.g. <% foo %>) for JS, but then this will block the not quite reusable between languages.

So, my question is: it is possible to display a mustache template inside of a mustache template? Did I miss something in the docs? Or it's just not possible?

Thanks!


Solution

  • You can also switch to different template tags just before the embedded template, and then back after you're done:

    something awesome with {{ tags }}!
    
    {{=[[[ ]]]=}}
    <script type="text/template" id="my-tpl">
      {{foo}}
    </script>
    [[[={{ }}=]]]
    
    back again with more {{ tags }}!