• <%= movies["" />
  • <%= movies["" />
  • <%= movies[""/>

    Looping through API with hbs

    1.1k Views Asked by At

    I'm coming from ejs. I had a function to loop though my API data like this:

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

    How can I use hbs to do the same? I tried this:

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

    but it doesn't display anything.

    Here is my 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 });
        });
    });
    

    How can I loop through those values on my API_Result.hbs?

    Example of search: Broomsticks

    {
    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",
    }
    

    Thank you

    1

    There are 1 best solutions below

    7
    Md Mahmudul Haque Fahim On BEST ANSWER

    Please look into below code. you have to run a loop as we do it inside js.

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