通过视图传递变量,使用 express 和 pug

Passing variables through the views, with express and pug

我在控件中的端点是这样的:

contoControl.js

var express = require('express');
var router = express.Router();
var passport = require('../config/passportConfig');
var riepilogoService = require('../services/riepilogoService');

/* GET home page. */
router.get('/', passport.ensureAuthenticated, function(req, res, next) {
    riepilogoService.getUserData(req.user.id, (userData) => {
        res.render('conto', {title: 'Home', userData: userData});
    });
});

每次我加载 'conto' 视图时,userData 变量都会从 db 更新并发送给它,视图中的 userData 是这样使用的,一切都很完美:

conto.pug

extends layout

block content
    body
        div.card-content
            ul.collection#listamovimenti(style='border-radius: 15px;')
                each movimento in userData.ultimiMovimenti
                    li.collection-item.avatar
                        if(movimento.importo > 0)
                            i.material-icons.circle.green(style='margin-top: 12px;')
                                | arrow_upward
                            span.title
                                | #{movimento.nomeMitt}
                            p
                                | #{movimento.descrizione}
                                br
                                | #{prettyDate(movimento.data)}

'conto' 视图扩展了布局,我什至想在布局中使用 userData 变量,例如做我在 'conto' 中做的同样的事情,但是看不到 userData 变量在布局中

layout.pug

doctype html
html(lang='it')
    head
        ...
    body
        ...
        //the same thing I do with userData in the 'conto' views
        ...
        .container
        block content

我认为由于没有为布局定义路由,所以不会传递和渲染任何内容。

要考虑,除非您打算用独特的内容替换子页面上的 block content,否则可以考虑使用 include。据我了解,块不是每个说 'building blocks of code',而是每个视图的可替换内容 'areas' 或 'blocks'。例如,在一个 block 中,你可以有一些独特的代码和一个包含更多代码的包含,所有这些都在一个块中,这样你就可以在其他页面上更灵活地编辑块内容。

我有几乎相同的设置并且在我的项目中有效。

当您将此行插入正文 layout.pug 时会发生什么? p #{userData[0].ultimiMovimenti} 或 p #{userData[0].ultimiMovimenti[0]}