pugjs / pug

Pug – robust, elegant, feature rich template engine for Node.js
https://pugjs.org
21.54k stars 1.96k forks source link

Pug accessed controller variable without passing it #3398

Closed dinhitcom closed 1 year ago

dinhitcom commented 1 year ago

Pug Version: 3.0.2

Node Version: 18.12.0

I have project using Express with pug then I found a strange behavior on my view. They somehow access some variable I didn't declare/pass. After a bit digging I found out that pug somehow be able to access controller variable that haven't declare with a var/let/const keyword. I'm not sure is it a bug or a feature.

Input JavaScript Values

module.exports = {
    renderLogin: (req, res) => {
        test_variable = "This variable has been passed"
        res.status(200).render('login', {
            message: req.query.message,
            icon: req.query.icon,
            alert_type: req.query.alert_type,
        });
    }
}

Input Pug

.container-fluid.vw-100.vh-100.bg-light
   h1=test_variable
   // - other form stuffs

Render view

image

johbenrivcar commented 1 year ago

If you assign a value to a variable name without declaring the variable with var/let/const then that variable is created in global context by default. So, once the renderLogin function has been run, then _testvariable has been created in global and is accessible to the js code in pug. I think this counts is a feature, not a bug.