【问题标题】:how to output data in hbs file如何在hbs文件中输出数据
【发布时间】:2020-10-04 15:50:22
【问题描述】:

index.hbs 代码:
这是 index.hbs 文件,我从 index.js 文件中传递数据。

```{{# each products}}
<div class="row">
{{# each this}}
<div class="col-sm-6 col-md-4">
        <div class="thumbnail">
            <img src="{{imagePath}}" alt="..." class="img-responsive">
            <div class="caption">
                <h3>{{title}}</h3>
                <p class="description">{{description}}</p>
                <div class="clearfix">
                    <div class="price pull-left">{{price}}</div>
                    <a href="#" class="btn btn-success pull-right" role="button">Button</a>
                </div>
            </div>
        </div>
    </div>
{{/each}}
</div>
{{/each}}```

index.js 代码:

var products=Product.find(function(err,docs){
    res.render('shop/index', { title: 'Shopping Cart', products:docs });    
});

mongob Schema中的数据是这样的

var products= [
new Product
({
    imagePath:'https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png',
    title:'Gothic video games',
    description:'Awesome Game!!',
    price: 20
    }),
new Product({
    imagePath:'https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png',
    title:'Gothic video games',
    description:'Awesome Game!!',
    price: 20
    }),
    new Product({
    imagePath:'https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png',
    title:'Gothic video games',
    description:'Awesome Game!!',
    price: 20
    }),
    new Product({
    imagePath:'https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png',
    title:'Gothic video games',
    description:'Awesome Game!!',
    price: 20
    }),
    new Product({
    imagePath:'https://upload.wikimedia.org/wikipedia/en/5/5e/Gothiccover.png',
    title:'Gothic video games',
    description:'Awesome Game!!',
    price: 20
    })
        
    ];

结果显示五个空列 div,然后是一个包含数据的列 div。请分享它的解决方案。

【问题讨论】:

  • 内部的 {{# each this}} 看起来没必要?或者我错过了什么?

标签: node.js mongodb handlebars.js


【解决方案1】:

去掉#和each之间的空格,应该是#each而不是#each。

例如

{{#each products}}

而且您不需要 2 个#each,只需 1 个就足够了。删除不需要的 {{# each this}}。

{{#each products}}
<div class="col-sm-6 col-md-4">
        <div class="thumbnail">
            <img src="{{imagePath}}" alt="..." class="img-responsive">
            <div class="caption">
                <h3>{{title}}</h3>
                <p class="description">{{description}}</p>
                <div class="clearfix">
                    <div class="price pull-left">{{price}}</div>
                    <a href="#" class="btn btn-success pull-right" role="button">Button</a>
                </div>
            </div>
        </div>
</div>
{{/each}}

因此,您将获得每种产品,并显示其字段。如果你想使用'this',那么你可以使用 {{this.imagePath}},但我相信它不是必需的,因为它可以工作。您可以自己测试它,它应该可以使用,也可以不使用,但它更容易阅读,因为您知道它指的是什么。

【讨论】:

    猜你喜欢
    • 2019-04-02
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2019-04-19
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多