首页 > 解决方案 > 除非将数据重新分配给另一个变量,否则车把不会呈现

问题描述

我的 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>

标签: handlebars.js

解决方案


你是如何传递res给渲染函数的?应该是这样的。

$("#room-list").html(render({ rooms: res }))

推荐阅读