Search code examples
node.jsexpressinheritancemodel-view-controllerpug

Passing variables through the views, with express and pug


My endpoint in the control is like this:

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});
    });
});

every time I load the 'conto' view, the userData variable is updated from db and sent to it, userData in the views is used like this and everything works perfectly:

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)}

the 'conto' view extends layout and I would like to use the userData variable even in layout, for example to do the same thing I do inside 'conto', but the userData variable is not seen in layout

layout.pug

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

Solution

  • I think since there is no route defined for layout there would be nothing to pass and render.

    To consider, unless you are intending to replace the block content on child pages with unique content then perhaps consider using include. Blocks as I understand aren't 'building blocks of code' per say but rather 'areas' or 'blocks' of replaceable content per view. eg inside a block you could have some unique code and an include with more code being pulled in, all inside a block so that on other pages you can edit the blocks contents more flexibly.