Patrioticcow
Patrioticcow

Reputation: 27058

how to append a handlebars template to a div with a certain id?

i have a simple template that i populate with some data then im trying to append it before one did, but it seems to stop working.

here is the jsfiddle

and the code:

<ul class="wall_message">
    <li id="168" class="msgid">
        <div id="commentbox2">
        </div>
    </li>
    <!-- in this case the json will be added only before `commentbox2`-->
    <li id="168" class="msgid">
        <div id="commentbox3">
        </div>
    </li>
</ul>




<script id="comment" type="text/x-handlebars-template">
                {{#each this}}
                        <div class="commentsp">{{comment}}</div>
                {{/each}}
</script>


<script>

//right now this json has only one main key (5), but it could have more
var data = {"5":
            {"id":"2", "comment":"xxxxxxxx"}
           }

/initiate the template
var template = Handlebars.compile( $('#comment').html() );

// place the json data in the template. the template will iterate through
msg = template(data);

jQuery.each(data, function(i, val) {
    console.log(val.id)

    //find the div with commentbox2 and add the msg before
    $('div#commentbox'+val.id).before(msg);
});
</script>

im not sure what i am doing wrong in this case.

any ideas?

thanks

Upvotes: 1

Views: 8656

Answers (1)

Julien Lafont
Julien Lafont

Reputation: 7877

I have tried to resolv your problem.

Your Json seems not "handlebar-compatible" for me. I have rewrited it with a root element, which will be used in the {{#each}} statement.

var data = { 
    'items': [
        {"id":"2", "comment": "xxxxxxxx"}, 
        {"id":"3", "comment": "yyyyyyy"}
    ]
};

var template = Handlebars.compile( $('#comment').html() );
var msg = template(data);

jQuery.each(data.items, function(i, val) { 
    $('div#commentbox'+val.id).before(msg);
});

See the complete demo here http://jsfiddle.net/nsvT3/11/

I hope it's what you want.

Upvotes: 1

Related Questions