0

我开始学习一些 NodeJ,并想创建一个小型路由。所以我在这里将这段代码用于我的 server.js

var express = require('express');
var app = express();

app.get('/profile/:id', function (req, res) { // The URL for localhost:8888/profile/Peter

  var user = null; // Read some data from the JSON file later on...

  res.render('index', { // Load the index file and set some variables
    content: 'Views/profile.pug'
    name: user.name,
    hitpoints: user.hitpoints,
    stamina: user.stamina,
    strength: user.strength });
});

app.listen(8888, function () {
  console.log('Server listening on Port 8888');
});

所以我的 index.pug 文件将处理变量并include用于加载模板

html

  link(rel='stylesheet', href='/CSS/requirements.css')
  script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js")

  body
    p 'TEST - This is on all pages'

    include content

所以我的模板需要来自服务器的用户变量

script(src="/Client/profile.js")

p 'Character:'
p = name

p 'Hitpoints:'
p = hitpoints

p 'Stamina:'
p = stamina

p 'Strength:'
p = strength

button(class='btn' onclick='back()') 'Back'

如何从 index.pug 获取信息并将其发送到 index.pug 包含的模板文件?

喜欢include content // and pass the needed variables

4

1 回答 1

0

重命名index.pughead.pug并添加为第一行

doctype html
html
  head
    link(rel='styleshe...

然后像这样替换你的身体部位:

  body
    block content

现在创建一个新文件profile.pug并添加为第一行

extends head.pug
block content
  script(src="/Client/profile.js")

  p 'Character:'

以及模板的其余部分

server.js,而不是渲染 index.pug,渲染profile.pug

res.render('profile',
  name: user.name,
  hitpoints: user.hitpoints,
于 2017-11-20T13:43:05.947 回答