如何将项目附加到现有handelbar模板中的列表中

how to append an item to a list in an existing handelbar template?

本文关键字:handelbar 列表 项目      更新时间:2023-09-26

我正试图在现有的手把模板中添加一个列表。下面的代码允许我添加注释,但为了使新注释与现有注释一起出现在列表中,我需要刷新。我想知道的是如何将新的注释附加到模板中现有的注释列表中。我已经包含了整个模板,但我试图添加新评论的地方是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
  }));