Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache JS Templating - How do I embed a variable in a script tag string?

I just started using Mustache and I like it so far, but this has me perplexed.

I am using the GitHub gist API to pull down my gists, and part of what I want to do is include the embedding functionality into my page. The problem is Mustache seems to not want to have anything to do with my dynamic script tag.

For example, this works fine:

<div class="gist-detail">
    {{id}} <!-- This produces a valid Gist ID -->
</div>

Additionally, this works perfect:

<div class="gist-detail">
    <script src='http://gist.github.com/1.js'></script> <!-- Produces the correct embed markup with Gist ID #1 -->
</div>    

If I try to pull these together, something goes terribly wrong:

<div class="gist-detail">
    <script src='http://gist.github.com/{{id}}.js'></script> <!-- Blows up! -->
</div>  

Chrome Inspector shows this:

GET https://gist.github.com/%7B%7Bid%7D%7D.js 404 (Not Found)

... which looks like to me something is weird with escapes or whatnot, so I switch over to the raw syntax:

<div class="gist-detail">
    <script src='http://gist.github.com/{{{id}}}.js'></script> <!-- Blows again! -->
</div>  

And I get the same result in Inspector:

GET https://gist.github.com/%7B%7B%7Bid%7D%7D%7D.js 404 (Not Found)

How do I get the correct values to embed in the script tag?

EDIT

I am injecting the template as follows (in document.ready:

function LoadGists() {
    var gistApi = "https://api.github.com/users/<myuser>/gists";

    $.getJSON(gistApi, function (data) {

        var html, template;
        template = $('#mustache_gist').html();

        html = Mustache.to_html(template, {gists: data}).replace(/^\s*/mg, '');
        $('.gist').html(html);
    });

}

The actually template is inside of a ruby partial, but it is wrapped in a div (not a script tag, is that a problem?) (that's hidden):

<div id="mustache_gist" style="display: none;">

    {{#gists}}
        <!-- see above -->
    {{/gists}}

</div>

I assume a div is ok rather than a script because in either case, I'm pulling the .html(). Is this a bad assumption?

like image 676
Evan Avatar asked Jan 29 '12 06:01

Evan


1 Answers

To avoid automatic escaping in Mustache use {{{token}}} instead of {{token}}.

like image 163
oarevalo Avatar answered Sep 23 '22 14:09

oarevalo