在Node.js中包含HTML文件
我似乎无法弄清楚如何使用Node.js包含文件。 所有其他问题似乎讨论包括其他JS文件,但我正在寻找相当于一个PHP包括(可以包含HTML内容的文件)。
通常在PHP中,我的视图文件是这样的:
...stuff <?php include 'header.php'; ?> <?php include 'nav.php'; ?> ... more stuff <?php include 'footer.php'; ?>
例如在nav.php
我有:
<nav role=navigation> <ul> <!-- links --> </ul> </nav>
Node中是否有类似的function,或者我必须改变开发Web应用程序的方式吗? 如果有帮助,我正在使用Express框架。
一个简短的,工作的例子将不胜感激。
不,这不是nodeJS的工作方式。 如果你想比较,比较nodejsruby或ASP.NET。 有翡翠,如dystroy说的,但如果你熟悉HTML语法,比如ectjs比如:
stuff... <div id="content">stuff</div> <% include 'footer.ect' %>
当然,如果有包含使用require
代码
有没有什么类似的直接进入nodejs。
但是很多使用nodejs的人也使用像express和template引擎这样的框架。
比如Jade让你做的包括 :
index.jade文件:
doctype html html include includes/head body h1 My Site p Welcome to my super lame site. include includes/foot
包含/ head.jade文件:
head title My Site script(src='/javascripts/jquery.js') script(src='/javascripts/app.js')
包括/ foot.jade文件:
#footer p Copyright (c) foobar
需要注意的是,在Ajax时代,单页面应用程序和JavaScript,模板包括在PHP的旧时代很less需要。 您可能需要先使用模板(例如使用Jade)稍微玩一下,然后才决定是否需要包含模板。
你可以用vash引擎。 以此布局页面为例:
<body> <!-- Body content --> <div>@html.block("body")</div> <!-- Render Page Specific Scripts Here --> @html.block("scripts") </body>
现在在你的其他观点中,你可以这样做:
@html.extend("layout", function(model){ <!-- main content of the page --> @html.block("body",function(model){ <h1>This will be the login page</h1> }) <!-- page specific scripts --> @html.block("scripts",function(model){ <scrip></script> }) })
希望这可以帮助!
假设我们必须在index.html中包含2个文件
最简单的方法
html index.html
<%include filename.extension%> <%include anotherfile.html%>
的node.js
var temp = require('templatesjs'); // ... ... ... fs.readFile("./index.html"){ if(err) throw err; var output = temp.set(data); res.write(output); res.end(); });
这两个文件将在您使用set()
时自动包含在index.html中
我已经使用模块templatesjs
$ npm install templatesjs
这里有一个很好的文档
github: templatesjs