我有两个文件。一个是哈巴狗文件:
doctype html
html
head
meta(charset='utf-8')
meta(name='viewport', content='width=device-width, initial-scale=1, shrink-to-fit=no')
link(href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', rel='stylesheet')
title Your first page
body
script(src='https://code.jquery.com/jquery-3.3.1.min.js')
script(src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js')
script(src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js')
第二个是JS文件:
var express = require('express'),
logger = require('morgan');
var app = express();
var x = 1;
var y = 2;
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.render('index', {pretty:true});
});
app.listen(3000, function () {
console.log('The application is available on port 3000');
});
现在,我想使用x和y变量,并使用pug文件显示它们。我怎样才能做到这一点?
答案 0 :(得分:1)
尝试一下。
app.get('/', function (req,res) {
res.render('index', { pretty: true, title: 'Hey', message: 'Hello there!'});
});
doctype html
html
head
meta(charset='utf-8')
meta(name='viewport', content='width=device-width, initial-scale=1, shrink-to-fit=no')
link(href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', rel='stylesheet')
title Your first page
title= title
body
script(src='https://code.jquery.com/jquery-3.3.1.min.js')
script(src='https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js')
script(src='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js')
h1=message
希望有帮助。
答案 1 :(得分:0)
在您的代码中,您已经将变量传递给模板(pug)。您可以用相同的方式进行操作:
app.get('/', function (req, res) {
res.render('index', {pretty:true, x: x, y: y});
});
x:
是“键”,而x
是对变量x的引用。与y相同的过程。
在您的哈巴狗文件中,例如:
h1 = x
h2 = y
希望我能帮上忙。