handlebars.js - 除非将数据重新分配给另一个变量,否则车把不会呈现
问题描述
我的 Handlebarsrender()
函数返回一个空字符串,除非我的 AJAX 响应中的数据被分配给一个新变量。我可以解决这个问题,但我很好奇我是否做错了什么导致它。
有问题的违规代码:
// Get the list of rooms from the server
$.ajax({
url: "/rooms",
method: "GET",
statusCode: {
200: (res) => {
// Must reassign res to another variable in order to render
const rooms = res;
$("#room-list").html(render({rooms}));
},
},
});
还应该注意的是res === rooms
退货true
。
我在哪里得到模板:
const template = $("#room-item-template").html();
const render = Handlebars.compile(template);
最后,HTML 模板本身:
<template id="room-item-template">
\{{#each rooms}}
<article class="room-item" id="\{{_id}}">
<a href="/chat?room=\{{_id}}">
<button class="room-btn">
<h3>\{{name}}</h3>
<p>\{{users.length}} / \{{capacity}}</p>
</button>
</a>
<a href="/rooms/config/\{{_id}}">
<button class="room-config-btn">Configure Room</button>
</a>
</article>
\{{/each}}
</template>
解决方案
你是如何传递res
给渲染函数的?应该是这样的。
$("#room-list").html(render({ rooms: res }))
推荐阅读
- java - 自动装配变量的方法为空
- node.js - 通过 http.get 将正文添加到字符串
- android - onFling 向上滑动也会触发向左滑动或向右滑动
- c++ - 通过引用开销与复制开销进行访问
- wordpress - 为什么 Wordpress Customizer 认为我的主题已损坏?
- node.js - Node.js 应用程序中的 Facebook Graph API 问题
- jsf - 尽管INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL = true,如何为空输入组件设置自定义非空值
- ansible - 在 Ansible 中迭代哈希只会将最后一个结果保存在寄存器中
- javascript - 如何有条件地使用开发或生产环境变量
- java - 在retun方法上封装运行时异常,还是生成异常方法?