车把每句话不循环

Handlebars each sentence not looping

我有这个模板

<table class="table">
    <thead>
        <tr>
        <th scope="col">#</th>
        <th scope="col">Nombre del foro</th>
        </tr>
    </thead>
    <tbody>

        {{#each data}}
        <tr>
            <th scope="row">{{ id }}</th>
            <td>{{name}}</td>
        </tr>
        {{/each}}

    </tbody>
</table>

使用此输入数据

[
{"id":1,"name":"Foro general"},
{"id":2,"name":"Otro foro"},
{"id":14,"name":"Nuevo foro"},
{"id":15,"name":"Nuevo foro"},
{"id":16,"name":"Nuevo foro"},
{"id":17,"name":"Nuevo foro"},
{"id":18,"name":"Nuevo foro"}
]

输出是这样的

<table class="table">
    <thead>
        <tr>
        <th scope="col">#</th>
        <th scope="col">Nombre del foro</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

我不知道为什么 JSON 被视为空对象数组。 知道我错过了什么吗?

编辑 2:删除不必要的混淆代码

forumListTemplate(data){
    var forumListTemplate = 
    `
    <table class="table">
        <thead>
            <tr>
            <th scope="col">#</th>
            <th scope="col">Nombre del foro</th>
            </tr>
        </thead>
        <tbody>
            {{#each data}}
            <tr>
                <th scope="row">{{ id }}</th>
                <td>{{name}}</td>
            </tr>

            {{/each}}
        </tbody>
    </table>
    `
    var forumListCompiled = compile(forumListTemplate);
    var forumListHTML = forumListCompiled(data);
    return forumListHTML;
}

我检查了那个结果returns上面提到的输入数据

尝试将具有字段 data 的对象传递给已编译的模板。

var forumListCompiled = compile(forumListTemplate);
var forumListHTML = forumListCompiled({data: data});
return forumListHTML;

对于您或其他查看此问题的人来说,它有什么价值(如果您致力于使用 Handlebars,可能没什么价值),您不需要第三方库即可在现代 JavaScript .您可以只使用 template strings

我知道您最初的问题是关于如何使用 Handlebars,但也许这对您现在或以后会有用。优点是,无需导入外部库并增加应用程序的大小:

const inputData = [
  {"id": 1, "name": "Foro general"},
  {"id": 2, "name": "Otro foro"},
  {"id": 14, "name": "Nuevo foro"},
  {"id": 15, "name": "Nuevo foro"},
  {"id": 16, "name": "Nuevo foro"},
  {"id": 17, "name": "Nuevo foro"},
  {"id": 18, "name": "Nuevo foro"}
]

function forumListTemplate(data){
    const trs = data.map(entry => (
            `<tr>
              <th scope="row">${entry.id}</th>
              <td>${entry.name}</td>
             </tr>`
             )
    )
    
    return `<table class="table">
              <thead>
                <tr>
                  <th scope="col">#</th>
                  <th scope="col">Nombre del foro</th>
                </tr>
              </thead>
              <tbody>
                ${trs}
              </tbody>
            </table>`
}

console.log(forumListTemplate(inputData));