如何执行express来将string解释为HTML代码?

我开始使用node.js,特别是express.js。

鉴于我喜欢尽可能干 ,我已经决定只有一个index.pug模板,其中有一个单一的HTML元素main.content身体。 实际内容由pug.renderFile()根据摘录创build,存储在<name>.pug文件中。

整个画面是这样的:

SERVER.JS

 response.render("index", { content: pug.renderFile(excerpt("aboutus"), { title: "About Us", subtitle: "Some subtitle here", article: "Some text here" }) }); 

ABOUTUS.PUG

 h1= title h3= subtitle article= article 

INDEX.PUG

 //- html-head-body routine main.content= content 

问题是, pug.renderFile()以string的forms返回HTML代码,而不是获取main.content元素内的main.content元素,我得到这个确切的string作为该元素的.innerHTML

那么,我的错误是什么?

这是可怕的做法。 你需要使用扩展。 不要打两个电话给哈巴狗。 你正在烘焙演示文稿到错误的层次。 这会在以后刺痛你

更何况,你迫使HTML进入一个中间string,并进行额外的function调用,无法优化。

SERVER.JS

 response.render("aboutus", { title: "About Us", subtitle: "Some subtitle here", article: "Some text here" }); 

ABOUTUS.PUG

 extends index block content h1= title h3= subtitle article= article 

INDEX.PUG

 // html-head-body routine main.content= content 

如果这没有意义的思考你的系统将如何扩展。 比方说,你有一个导航栏的一个帕格文件,一个页脚和一个头等等。你要把它们串起来,并传递给你的index.pug在每个请求?

  1. 这将是非常干的。
  2. 这将是缓慢的。
  3. 这将是内存密集型的。
  4. 这将是一个维护噩梦。

按照惯例,它会做得很好。