Node JS 将变量传递给 Jade / Pug

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38044237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:20:50  来源:igfitidea点击:

Node JS Pass a Variable to Jade / Pug

node.jspug

提问by The Hawk

For some reason I can't pass a variable to the pug template with Node JS.

出于某种原因,我无法使用 Node JS 将变量传递给 pug 模板。

app.get("/", function (req, res) {
    res.render('index', { hello : 'Hey'} )
})

....

....

extends layout.pug

block content
    h1 #{hello} guy

This just returns "guy" in the index.html file

这只是在 index.html 文件中返回“guy”

回答by Seetpal singh

I think you are using JADE coding (#{hello}) with "pug"(updated jade) plugin with static .html -- completely wrong.

我认为您正在使用带有静态 .html 的“pug”(更新的 jade)插件的 JADE 编码(#{hello})——完全错误。

follow the lines below:

遵循以下几行:

  1. use this first

    app.set('views', __dirname + '/public/views');
    app.set('view engine', 'pug');
    
  2. than pass this to first visit

    app.get('/', function (req, res) {
        res.render('index', { title: 'Hey', message: 'Hello there!'});
    });
    
  3. than echo in template file "index.pug" in "/public/views"

    html
       head
       title= title
    body
       h1= message
    
  1. 先用这个

    app.set('views', __dirname + '/public/views');
    app.set('view engine', 'pug');
    
  2. 比将其传递给第一次访问

    app.get('/', function (req, res) {
        res.render('index', { title: 'Hey', message: 'Hello there!'});
    });
    
  3. 比在“/public/views”中的模板文件“index.pug”中回显

    html
       head
       title= title
    body
       h1= message
    

回答by Giorgi Maisuradze

Try this.. works for me.

试试这个..对我有用。

nodejs part / index.js

nodejs 部分 / index.js

const router = require('express').Router();
router.get('/', (req, res, next) => {
    const testObj = {hello: 'Hey'};
    res.render('index', { testObj: JSON.stringify(testObj) });
});

pug/jade part / (index.pug)

哈巴狗/玉器部分/(index.pug)

script.
    var testObj = !{testObj};

i'm using pugversion: 2.0.3

我正在使用哈巴狗版本:2.0.3