How to display MySQL “result” object to user with express-handlebars?

我是研究僧i 提交于 2020-08-12 01:41:26

问题


I currently have a query in my node js that looks like this:

app.get('/fav/books', function(req, res){
var sql = ("SELECT title, pictureUrl, author, description, genre FROM books")
  connection.query(sql, function(err, result){
    if(err) {
      console.log('Error in the query.');
    } else {
      console.log('Success!\n');
      console.log(result);
      var book = result;
      return book;
    }
  });
});

And outputs to console like this: Console Output

I want to "return book;" to the user with handlebars in a sort of card output like this:

<div class="page-carousel">
  <div class="panel id1">
    <img href="pictureUrl"/>
    <h3>title</h3>
    <p><strong>author</strong></p>
    <p>description</p>
    <p>genre</p>
  </div>
</div>

The panel would be the ID of the Book as it needs to create as many panels as there are IDs. The book information would be as is.


回答1:


Angularjs is just perfect for this. Assign this response object to a $scope variable say $books.Then you could do this:

<div class="page-carousel">
  <div ng-repeat="x in books" class="panel {{x.id}}">
    <img href="{{x.pictureUrl}}"/>
    <h3>{{x.title}}</h3>
    <p><strong>{{x.author}}</strong></p>
    <p>{{x.description}}</p>
    <p>{{x.genre}}</p>
  </div>
</div>



回答2:


I can see the books you are returning is an array of objects, each object containing a book info in this case we need to iterate in a loop in handlebars like -

{{#each book}}
  <div class="page-carousel">
    <div class="panel id1">
      <img href={{book.pictureUrl}}/>
      <h3>{{book.title}}</h3>
      <p><strong>{{book.author}}</strong></p>
      <p>{{book.description}}</p>
      <p>{{book.genre}}</p>
    </div>
  </div>
{{/each}}


来源:https://stackoverflow.com/questions/44713393/how-to-display-mysql-result-object-to-user-with-express-handlebars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!