1

I am using Mustache.js to format a response from a jQuery getJSON() request. The getJSON request gets a list of images names. I want to display a series of these images at the end of my existing content when the call is made.

The JSON that is returned looks like this:

[
  {"id":{"_time":1351063373,"_machine":56912161,"_inc":1690583039,"_new":false},"url":"5.jpg","tags":[]},
  {"id":{"_time":1351063237,"_machine":56912161,"_inc":1690583038,"_new":false},"url":"Repinzle-Logo.png", "tags":[]},
  {"id":{"_time":1351063186,"_machine":56912161,"_inc":1690583037,"_new":false},"url":"21.jpg","tags":[]}}
]

I am parsing it with the each function ... my AJAX request (with jQuery looks like this):

<script type="text/javascript">
    var imageNum=20;
    var imageCount=0;

    function getMoreImages(){
        imageCount=imageCount+imageNum;
        $.getJSON("/getImages", { start: imageNum, count: imageCount },
            function(data){
            $.each(data, function(key, val) {
                // do stuff with val.url

                var url = val.url;
                var template = $('#item-tpl').html();
                var newitem = Mustache.to_html(template, url);
                    $('#main').append(newitem);
                });     
              });
    }
</script>

And here is the mustache.js template

<script id="item-tpl" type="text/html">
    <div><img src="https://myurlstem.com/mydir/{{url}}" class="item"></div>
</script>

As far as I can see I've set everything up correctly, but for some reason url is not being sent to the template correctly.

1
  • Everything is working except the Url variable is never rendered. Commented Oct 24, 2012 at 12:29

1 Answer 1

2

You need to pass an object to the to_html method.

var newitem = Mustache.to_html(template, { url: url });

Normally, I think you'd pass your entire model or collection.

Sign up to request clarification or add additional context in comments.

2 Comments

Later I'll pass the whole list, I just want to get a simple version working. I think url and url might be conflicting, have changed the names.
Got some strange error not related to this question, will sort it out and report back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.