javascript - 如何将项目附加到现有 Handlebars 模板中的列表?

标签 javascript jquery templates handlebars.js

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

<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
  }));

关于javascript - 如何将项目附加到现有 Handlebars 模板中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26879327/

相关文章:

javascript - 如何显示输入字段的 id 以及相应的值

javascript - 使用 javascript 在循环中插入 JSON 值

javascript - 更改单页 Angular 应用程序中的 View

jquery - 如何使用 jQuery 将动画恢复为默认值

c# - 在jquery中设置对话框文本

javascript - 如何在不缩放内容的情况下更改 html5 Canvas 的尺寸

javascript - highcharts - 如何按总计对 xAxis 类别进行排序?

c++ - 模板类的转换

C++ 删除指针

c++ - 数组元素的总和作为 constexpr