Underlining me was very puzzled! In my code, everything works with regards to retrieving data after $ .when. console.log (messages); works, but when I try to pass it to the template and link
<h1><%=posts.id %></h1>
I get the message "Uncaught ReferenceError: messages not defined" in the line
$("#target").html(_.template(template,posts));
Here is the whole page
<!DOCTYPE html> <html> <head> <script src="js/api.js"></script> <link href="css/styles.css" media="" rel="stylesheet" type="text/css" /> </head> <body> <div id="target"></div> <script type="text/template" id="template"> <h1><%=posts.id %></h1> </script> <script src="js/jquery-1.9.1.min.js"></script> <script src="js/underscore.js"></script> <script type="text/javascript"> $.when(results).done(function(posts){ var template = $("#template").html(); console.log(posts); $("#target").html(_.template(template,posts) ); }); </script> </body>
[Object] 0: Object created_at: "2013-04" id: "444556663333" num_comments: 1 num_likes: 0 text: "<p>dfgg</p>" title: "title1" updated_at: "2013-04" user: Object first_name: "bob" id: "43633" last_name: "ddd"
**** Upadated ****** Thanks to all of you, I got my templates. _.each loops through an array of objects and populates html fragments and data from the API. Now, what I need to do is open open modal content with specific messages. I am struggling with my .click event. All different modal data fills in the correct data (when hidden, bootstrap modal), but I'm not sure how to refer to them when I click on their corresponding div. I always get a message for the first message.
$(".datachunk").click(function (){ $("#myModal").modal(); });
.datachunk refers to the current div.datachunk that you clicked on. Here is my template:
<script type="text/template" id="template"> <% _.each(posts,function(post){ %> <div class = "datachunk borderBottom"> <div class="openModall"><i class="icon-plus-sign-alt"></i> </div> <h2><%= post.title %></h2> <div class="postInfo"> <p><%= post.user.first_name %><%= post.user.last_name %></p><p> <% var date=moment(post.created_at).format("M/DD/YYYY");%> <%= date %></p> </div> </div> <% }) %> <% _.each(posts,function(post){ %> <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">Γ</button> <div class="datachunk"> <div class= "postInfo"> <h2><%= post.title %></h2> <p><%= post.user.first_name %><%= post.user.last_name %></p> </div> </div> </div> <div class="modal-body"> <p><%=post.text %></p> </div> </div> <% }) %> </script>
source share