Search code examples
javascripttemplateshandlebars.jsmustachegenshi

How to render a javascript template inside Genshi?


I'd like to render a mustache/handlebars template inside a genshi template. Genshi seems to raise a TemplateSyntaxError because of the mustache tags.

I've tried to put CDATA tags, as posted here, either inside and outside <script>:

<script id="some-template" type="text/x-mustache-template">
    <![CDATA[
    ... my template here ...
    ]]>
</script>

Since I do $('#some-template').html(), Handlebars just renders the CDATA tag together with the rest of the html, which messes the result.

<![CDATA[
<script id="some-template" type="text/x-mustache-template">
    ... my template here ...
</script>
]]>

This way, the browser comments the first <script> tag.

Also, commenting the CDATA with <!-- --> raises the error, and inside the script with /* */ just causes Handlebars to print it as is.

Is there any way to tell Genshi not to parse a chunck of the template?

Thanks!


Solution

  • Not sure if this helps, but I ran into a similar problem.

    I have a chunk of markup that is being run through an XML parser, which adds a handlebars template to the DOM that will later be compiled by script.

    In order to get the handlebars template past the XML parser, I needed to wrap with a CDATA block, but that was causing similar issues to yours. If I put the CDATA inside the script tags, the first bit of template markup was being swallowed in a comment. If I put them outside, the entire template was being commented and was unreachable by the script call to compile it.

    I was able to get around it by inserting an HTML comment as an unnecessary shield to get swallowed, like so:

    <div id="contentChunk">
        <div id="blah" class="foo">
            Some vanilla HTML being added.
        </div>
        <script id="hbTemplate" type="text/x-handlebars-template">
            <![CDATA[
            <!-- blocker comment: first html node of handlebars script gets swallowed. -->
            {{#each data.items}}
            <div id="item{{id}}">{{{name}}}</div>
            {{/each}}
            <!-- ]]> -->
        </script>
    </div>
    

    I also wrapped the trailing CDATA close tag in comments, otherwise I was getting a literal ]]> to render.