【问题标题】:Mustache issue with array of objects对象数组的胡子问题
【发布时间】:2022-02-08 19:02:36
【问题描述】:

所以我搜索了类似的问题并应用了他们的答案,但它似乎不适用于我的情况。令人沮丧,因为它应该很简单。

所以,我使用 mustache 模板来渲染来自带有套接字的节点服务器的数据。

它适用于一个对象,但是当我尝试遍历一组对象时,它只会呈现一个空白页面。

这是我的socket,push只是为了模拟我接下来要做什么(在数组中获取一个新对象)

let productsTab = [{
    prodName: prodName,
    prodPrice: prodPrice,
    quantity: quantity,
    quantityUnit: quantityUnit,
    isQuantityManual: isQuantityManual,
    hasQuantityUnit: hasQuantityUnit,
    totalPrice: totalPrice
}];

productsTab.push({
    prodName: prodName,
    prodPrice: prodPrice,
    quantity: quantity,
    quantityUnit: quantityUnit,
    isQuantityManual: isQuantityManual,
    hasQuantityUnit: hasQuantityUnit,
    totalPrice: totalPrice
});

res.render('displayProduct', productsTab);

这是我的数组的日志

[
  {
    prodName: 'name',
    prodPrice: 'price',
    quantity: '1',
    quantityUnit: '',
    isQuantityManual: false,
    hasQuantityUnit: false,
    totalPrice: 'price'
  },
  {
    prodName: 'name',
    prodPrice: 'price',
    quantity: '1',
    quantityUnit: '',
    isQuantityManual: false,
    hasQuantityUnit: false,
    totalPrice: 'price'
  }
]

最后这是我的胡子模板

{{#productsTab}}
<div>
    <div>
        {{ prodName}}
    </div>
    <div>
        {{{ prodPrice }}}
        {{ #hasQuantityUnit }}
        text
        {{ /hasQuantityUnit }}
    </div>
</div>
<div>
    <div>
        x {{ quantity }} {{ quantityUnit }}
        {{ #isQuantityManual }}
            (MAN)
        {{ /isQuantityManual }}
    </div>
    <div>
        = {{{ totalPrice }}}
    </div>
</div>
{{/productsTab}}

它只适用于没有 {{#}} 循环功能的对象(不是数组),因此问题必须来自数组...

我需要帮助

【问题讨论】:

    标签: javascript node.js sockets mustache


    【解决方案1】:

    好的,我明白了。这是我渲染模板的时候

    res.render('displayProduct', productsTab);
    

    这仅在您传递的道具是一个对象时才有效,但我必须遍历一个对象数组,所以我这样做了:

    res.render('displayProduct', { productsTab });
    

    希望它能帮助像我这样大脑冻结的人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      相关资源
      最近更新 更多