如何在Pug中渲染详细视图而不是其所有对象?

时间:2017-09-13 01:47:04

标签: javascript node.js express pug sequelize.js

我正在使用Express,Node和Pug构建应用。在Express中,我有GET books/:id的端点。我抓住了中间件函数中的所有书籍,然后渲染了视图。在视图中,我遍历所有书籍,而不是只显示一本书籍细节,而是显示所有书籍。我如何只渲染一本书的详细信息视图?

这是详细页面端点:

// GET the book detail page
router.get('/:id', (req, res, next) => {
bookQuery = Book.findAll({
    include: [
        { model: Loan }
    ],
    order: [["title", "DESC"]]
}).then((books) => {
    console.log(books);
    res.render('book_detail', {
        books: books,
        // title: loans.Book.title,
        // author: loans.Book.author,
        // genre: loans.Book.genre,
        // first_published: loans.Book.first_published,
        // patronFirstName: loans.Patron.first_name,
        // patronLastName: loans.Patron.last_name,
        // loanedOn: loans.loaned_on,
        // return_by: loans.return_by,
        // returned_on: loans.returned_on

    });
});
});

以下是观点:

extends ./layout
block content
    body
        each book in books
            h1 Book: #{book.title}
            form
                p
                    label(for='title') Title
                    input#title(type='text', value=book.title)
                p
                    label(for='author') Author
                    input#author(type='text', value=book.author)
                p
                    label(for='genre') Genre
                    input#genre(type='text', value=book.genre)
                p
                    label(for='first_published') First Published
                    input#first_published(type='text', 
value=book.first_published)
                p
                    input(type='submit', value='Update')
            h2 Loan History
            table
                thead
                    tr
                        th Book
                        th Patron 
                        th Loaned on
                        th Return by 
                        th Returned on
                        th Action
                tbody
                    tr
                        td
                            a(href=`/books/book_detail`)= book.title
                        td
                            //- a(href=`/patrons/patron_detail`)=book.Loan.first_name + ' ' + book.Loan.last_name
                        if book.Loan
                            a(href='patron_detail.html')
                            td= book.Loan.loaned_on
                            td= book.Loan.return_by
                            td= book.Loan.returned_on
                            td
                                a.button(href='return_book.html') Return Book

1 个答案:

答案 0 :(得分:1)

这与帕格无关。帕格只是渲染数据。

问题是您使用的是Book.findAll()。这得到了一系列书籍。您应该使用Book.findOne()来获取单个图书。您还需要指定where: { id: req.params.id }以查找URL中提供了ID的一本书。

您可能还想将变量books更改为book。并且视图中的行each book in books是不必要的。

Model Usage section of the manual有很多查询示例。我觉得比上面链接的API参考更容易阅读。