通过hbs遍历API

时间:2018-09-30 17:25:02

标签: javascript node.js handlebars.js express-handlebars handlebarshelper

我来自ejs。我有一个循环遍历我的API数据的函数,如下所示:

<p><% data["Search"].forEach(function(movies){ %>
    <li><strong><%= movies["Title"] %></strong> - <%= movies["Year"] %> - <%= movies["Type"] %></li>
<% }) %></p>

如何使用hbs进行相同操作?我尝试过:

<div>
    {{#each data}}
        <div class="row">
            <div class="col-md-12">
                {{Title}}
            </div>
        </div>
    {{/each}}
</div>

但它不会显示任何内容。

这是我的 app.js

const   express     = require("express"),
        request     = require("request"),
        bodyParser  = require("body-parser"); 

var     app         = express();

app.use(express.static("public")); 
app.set("view engine", "hbs"); 
app.use(bodyParser.urlencoded({ extended: true })); 

app.get("/moviesearch", function(req, res){
    res.render("moviesearch");
});


app.get("/movieResults", function (req, res) {
    var user = req.query.getValue;
    var url = "http://www.omdbapi.com/?s=" + user + "&apikey=...";
    request(url, function (error, response, body) {
        var data = JSON.parse(body);
        res.render("API_Results", { data: data });
    });
});

如何在API_Result.hbs上遍历那些值?

搜索示例:扫帚

{
Search: [
{
Title: "Bedknobs and Broomsticks",
Year: "1971",
imdbID: "tt0066817",
Type: "movie",
Poster: "https://m.media-amazon.com/images/M/MV5BMTUxMTY3MTE5OF5BMl5BanBnXkFtZTgwNTQ0ODgxMzE@._V1_SX300.jpg",
},
{
Title: "When Broomsticks Were King",
Year: "2001",
imdbID: "tt1418965",
Type: "movie",
Poster: "N/A",
},
],
totalResults: "5",
Response: "True",
}

谢谢

1 个答案:

答案 0 :(得分:0)

请查看以下代码。您必须像在js中那样运行一个循环。

<div>
    {{#each data.Search}}
        <div class="row">
            <div class="col-md-12">
                {{Title}}
            </div>
        </div>
    {{/each}}
</div>