[英]how to append an item to a list in an existing handelbar template?
我試圖在現有車把模板中添加一個列表。 下面的代碼允許我添加評論,但是為了使新評論與需要刷新的現有評論一起出現在列表中。 我想知道的是如何將新評論添加到模板中的現有評論列表中。 我已經包括了整個模板,但是我要添加新注釋的地方是ID為bodyOfComments的ul。 謝謝您的幫助。
var comment_post = function() {
// console.log($(this).attr("data-id"))
$.ajax({
url: 'http://localhost:3000/comments',
type: 'POST',
data: {comment: {
body: $('#content').find('input[name="createComment"]').val(),
user_id: 1,
image_set_id: $(this).attr("data-id")}
}
}).done(function(response) {
console.log(response);
var template = Handlebars.compile($('#imageSetTemplate').html());
$('#bodyOfComments').append(template({
comment: response
}));
});
};
$(document).ready(function () {
$('#content').on('click', '#submitComment', comment_post)
});
以下代碼是html文件中的車把模板
<script id="imageSetTemplate" type="text/x-handlebars-template">
<h1>{{image_set.voting_criteria}}</h1>
<div class="continer">
<div class="row">
{{#each image_set.images}}
<div class = "col-xs-4"><img src={{this.image_url}}></div>
{{/each}}
</div>
</div>
<ul id="bodyOfComments">
{{#each image_set.comments}}
<li> {{this.body}} </li>
{{/each}}
</ul>
<button type="submit" id="submitComment" data-id={{image_set.id}}>Create Comment</button>
<input name="createComment" id="commentBody">
</script>
將注釋模板移到單獨的模板中。
<script id="commentsTemplate" type="text/x-handlebars-template">
{{#comments}}
<li> {{.}} </li>
{{/comments}}
</script>
然后,您可以添加如下內容。
var template = Handlebars.compile($('#commentsTemplate').html());
$('#bodyOfComments').append(template({
comments: response
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.