Node JS如何将变量传递给Jade/Pug模板?

26

由于某些原因,我无法通过Node JS将变量传递到pug模板。

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

....

extends layout.pug

block content
    h1 #{hello} guy

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


你可以再加入一些代码吗?app是什么?layout.pug有什么内容? - chharvey
2个回答

23

我认为你正在使用JADE代码 (#{hello}) 与 "pug" (更新版的jade) 插件和静态 .html 文件-- 这是完全错误的。

按照以下步骤进行:

  1. 首先使用这个。
app.set('views', __dirname + '/public/views');
app.set('view engine', 'pug');
  1. 然后将这个传递给第一次访问
app.get('/', function (req, res) {
   res.render('index', { title: 'Hey', message: 'Hello there!'});
});
  1. 然后在位于"/public/views"的模板文件"index.pug"中进行回显
html
  head
  title= title
body
  h1= message

给我你的目录结构快照
展示给我你的服务器文件app.set('views', __dirname + '/public/views'); app.set('view engine', 'pug'); 然后将这个传递给首次访问 app.get('/', function (req, res) { res.render('index', { title: 'Hey', message: 'Hello there!'}); });
- Seetpal singh
现在它只是说“Express” https://github.com/jpking72/nodejsfiddle.git - The Hawk
我遇到了同样的问题,显然@Seetpalsingh不确定TheHawk和我哪里做错了。 - Ande Caleb

15

试一下这个... 对我有用。

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部分 / (index.pug)

script.
    var testObj = !{testObj};

我正在使用 pug 版本:2.0.3


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接