除非将数据重新分配给另一个变量,否则车把不会呈现
Handlebars not rendering unless data is reassigned to another variable
我的 Handlebars render()
函数 returns 一个空字符串,除非我的 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
returns 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 }))
我的 Handlebars render()
函数 returns 一个空字符串,除非我的 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
returns 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 }))