【问题标题】:Can't print element of array in handlebars template无法在车把模板中打印数组元素
【发布时间】:2020-07-26 16:31:38
【问题描述】:

我正在尝试将产品列表打印到我的车把视图之一,但它不允许我打印传入数组中的一个对象的特定属性。

store.js:

这是我用来渲染把手视图的:

res.render("products.handlebars", { products });

我在“产品”传递到上面一行之前记录了它,它是一个对象数组

在 products.handlebars 文件中:

这会打印整个数组以及 products.handlebars 视图中对象的所有内容

{{#each products}}
{{this}}
{{/each}}

但是如果我想像这样打印任何对象的属性:

{{#each products}}
{{this.title}}
{{/each}}

什么都没有出现,实际上什么都没有。没有错误,没有“未定义”,什么都没有。

我很确定我在 {{this.title}} 中的语法是错误的,但我不确定。我在另一个项目中使用了这个确切的代码,它工作得很好。我不知道我在这里做错了什么。

作为参考,我在控制台记录了我在 res.render 之前传入的数组,它看起来很好。这是数组元素的样子(这只是第一个元素):

{
title: 'Samsung Galaxy S20 Ultra 1TB',
price: 1999.99,
description: 'Lorem ipsum dolor...',
quantity: 10,
category: 'Mobile',
bestSeller: false,
imgPath: '/public/images/products/galaxys20ultra.png',
}

【问题讨论】:

标签: javascript html node.js express-handlebars


【解决方案1】:

我想通了。默认情况下,快速车把的最新更新禁用了对对象属性的访问。您需要在 app.engine 函数中重新启用它。

https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access

【讨论】:

    猜你喜欢
    • 2019-11-05
    • 1970-01-01
    • 2013-08-25
    • 2022-07-12
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2016-11-30
    相关资源
    最近更新 更多