【问题标题】:Node JS Pass a Variable to Jade / PugNode JS 将变量传递给 Jade / Pug
【发布时间】:2016-10-28 21:26:57
【问题描述】:

由于某种原因,我无法使用 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 有什么?

标签: node.js pug


【解决方案1】:

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

按照以下几行:

  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('视图引擎', '哈巴狗');而不是将其传递给第一次访问 app.get('/', function (req, res) { res.render('index', { title: 'Hey', message: 'Hello there!'}); });
  • 现在它只是说“快递”github.com/jpking72/nodejsfiddle.git
  • 我遇到了同样的问题,显然@Seetpalsingh 不确定 TheHawk 和我做错了什么。
【解决方案2】:

试试这个..对我有用。

nodejs 部分/index.js

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

哈巴狗/翡翠部分 / (index.pug)

script.
    var testObj = !{testObj};

我正在使用 pug 版本:2.0.3

【讨论】:

    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多