我正在开始使用node.js,特别是express.js。
鉴于我喜欢成为 D.R.Y.尽可能地,我决定只有一个 index.pug
- 具有单个 HTML 元素的模板 main.content
在 body 里。实际内容由 pug.renderFile()
创建,基于摘录,存储于 <name>.pug
文件。
全图是这样的:
SERVER.JS
response.render("index", {
content: pug.renderFile(excerpt("aboutus"), {
title: "About Us",
subtitle: "Some subtitle here",
article: "Some text here"
})
});
关于我们.PUG
h1= title
h3= subtitle
article= article
INDEX.PUG
//- html-head-body routine
main.content= content
问题是 pug.renderFile()
以字符串形式返回 HTML 代码,而不是在 main.content
中获取三个元素元素,我得到这个确切的字符串为 .innerHTML
这个元素。
那么,我的错误是什么?
最佳答案
这是一种可怕的做法。您需要使用扩展。不给哈巴狗打两次电话。您将演示文稿烘焙到了错误的层中。这稍后会刺痛你。
更不用说,您将 HTML 强制放入中间字符串并进行无法优化的额外函数调用。
SERVER.JS
response.render("aboutus", {
title: "About Us",
subtitle: "Some subtitle here",
article: "Some text here"
});
关于我们.PUG
extends index
block content
h1= title
h3= subtitle
article= article
索引.PUG
// html-head-body routine
main.content= content
如果这没有意义,请考虑一下您的系统将如何扩展。假设您有一个用于导航栏的 pug 文件,一个用于页脚,一个用于页眉等等。您要将它们全部串在一起并在每次请求时将它们传递到您的 index.pug
中吗?
- 这将非常反 DRY。
- 那会很慢。
- 这会占用大量内存。
- 这将是一场维护噩梦。
关注the convention它会对你有好处的。
关于node.js - 如何强制express将字符串解释为HTML代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41625142/