使用 node.js 包含 HTML 块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16369649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Include HTML blocks Using node.js
提问by Jeremythuff
This is what I want but probably can't have:
这就是我想要的,但可能没有:
Using node.js and express and maybe ejs, I would like to, while writing a regular HTML file in my client dir, server-side-include a template block of HTML. It would be cool also if I could pass variables into the include from the HTML document.
使用 node.js 和 express 或者 ejs,我想在我的客户端目录中编写一个常规的 HTML 文件时,服务器端包含一个 HTML 模板块。如果我可以将变量从 HTML 文档传递到包含中,那也会很酷。
Sooo something like:
像这样:
<!doctype html>
<html>
<head>
<%include head, ({title: "Main Page"}) %>
</head>
<body>
<% include header, ({pageName: "Home", color: "red"}) %>
...
<<% include footer%>>
</body>
</html>
Is there anyhting in node world that works like this? Or any thing that comes close and that could be maybe adapted for this functionality? I would not use it exactly in the way indicated here, but this is the functionality that I am looking for.
节点世界中有没有像这样工作的东西?或者任何接近并且可以适应此功能的东西?我不会完全按照此处指示的方式使用它,但这是我正在寻找的功能。
I have looked into jade, handlebars, ember and ejs, and ejs seems to come the closest. Maybe one of these does this already, but I am just confused about the implementation.
我研究过玉、车把、余烬和 ejs,而 ejs 似乎最接近。也许其中一个已经做到了,但我只是对实现感到困惑。
Any suggestions would be great!
任何建议都会很棒!
回答by Jeremythuff
OK I got it...
好,我知道了...
server.js
服务器.js
var express = require('express');
var server = express();
var ejs = require('ejs');
ejs.open = '{{';
ejs.close = '}}';
var oneDay = 86400000;
server.use(express.compress());
server.configure(function(){
server.set("view options", {layout: false});
server.engine('html', require('ejs').renderFile);
server.use(server.router);
server.set('view engine', 'html');
server.set('views', __dirname + "/www");
});
server.all("*", function(req, res, next) {
var request = req.params[0];
if((request.substr(0, 1) === "/")&&(request.substr(request.length - 4) === "html")) {
request = request.substr(1);
res.render(request);
} else {
next();
}
});
server.use(express.static(__dirname + '/www', { maxAge: oneDay }));
server.listen(process.env.PORT || 8080);
and in /www I have the following .html files:
在 /www 我有以下 .html 文件:
index.html
索引.html
{{include head.html}}
{{include header.html}}
<p class="well">Hello world!</p>
{{include footer.html}}
head.html
头文件
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
{{include include.css.html}}
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
</head>
<body>
include_css.html
include_css.html
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="stylesheet" href="css/main.css">
header.html
标题.html
<div class="well">
<h1>HEADER</h1>
</div>
footer.html
页脚.html
<div class="well">
<h1>FOOTER</h1>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src='//www.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
It all comes through, even includes in includes and static content. It is all performed on html files, and in a context that feel like vanilla web authoring.
这一切都通过了,甚至包括在包含和静态内容中。这一切都是在 html 文件上执行的,并且在感觉像 vanilla web 创作的上下文中。
++++Oops+++++ Well I almost all of it. I forgot that I also wanted to be able to pass variables into the include from the templates. I haven't tried that yet... any ideas?
++++哎呀++++++ 嗯,我几乎所有的。我忘了我还希望能够将变量从模板传递到包含中。我还没有尝试过……有什么想法吗?
++++Update+++++
++++更新++++++
Ok I figured it out.
好吧,我想通了。
Thisdiscussion made it clear, i guess i just didn't know enough about how ejs worked.
这个讨论说得很清楚,我想我只是对 ejs 的工作原理了解得不够多。
I have changed index.html to begin with variable declarations:
我已将 index.html 更改为以变量声明开头:
{{
var pageTitle = 'Project Page';
var projectName = 'Project Title';
}}
and then you can call these variables from within the includes, no matter how deeply they are nested.
然后您可以从包含中调用这些变量,无论它们嵌套多深。
So for instance, index.html includes start.html which includes header.html. Within header .html I can call {{= projectName}} within the header even though it was declared inside index.html.
例如,index.html 包含 start.html,而 start.html 包含 header.html。在 header .html 中,我可以在 header 中调用 {{= projectName}},即使它是在 index.html 中声明的。
I have put the whole thing on github.
我已经把整个东西放在了github 上。
回答by furydevoid
I would recommend nunjucksor pejs. Nunjucks is jinja-inspired, while pejs is just ejs + inheritance, block, and file support.
我会推荐修女或pejs。Nunjucks 受 jinja 启发,而 pejs 只是 ejs + 继承、块和文件支持。
pejs has some issues with space chomping at the moment, but it's still pretty useful. Of the two, I prefer the separation layer that comes with nunjucks.
pejs 目前在空间压缩方面存在一些问题,但它仍然非常有用。在这两者中,我更喜欢 nunjucks 附带的分离层。
Jadeis pretty cool and has the feature-set you're looking for, but it has a very unique syntax. References for jade: template inheritance, blocks, includes
回答by Imtiaz Chowdhury
Keep it simple, use templatesjs
保持简单,使用templatesjs
this can be done easily using templatesjs
这可以使用templatesjs轻松完成
html file[index.html]:
html 文件 [index.html]:
<head>
<title> <%title%> </tile>
</head>
<body>
<%include header.html%>
........
<%include footer.html%>
</body>
</html>
now in node.js file:
现在在 node.js 文件中:
var tjs = require("templatesjs")
fs.readFile("./index.html", function(err,data){ // provided the file above is ./ index.html
if(err) throw err;
tjs.set(data); // invoke it
tjs.render("title", "home");//render the page title
});
you are done . templatesjs witll automatically include header.html and footer.html all you have to do is to render the page title.
你完成了。templatesjs 会自动包含 header.html 和 footer.html,你所要做的就是渲染页面标题。
a good help can be found here
可以在这里找到很好的帮助
- installation:
$ npm install templatesjs
- 安装:
$ npm install templatesjs
Hope This Helps
希望这可以帮助
回答by Sijin K
var express = require('express');
var app = express();
var path = require('path');
app.get("/" ,(req,res) => {
res.sendFile(path.join(__dirname+'../../templates/index.html'));
});
app.use(express.static(path.join(__dirname+'../../templates/public')));
This way you can call HTML where ever the folder that contains HTML. if you want to include CSS and Javascript use express.static see the last line of code
通过这种方式,您可以在包含 HTML 的文件夹中调用 HTML。如果你想包含 CSS 和 Javascript 使用 express.static 看最后一行代码
回答by 0xception
Jade does allow server side includes of HTML blocks and any locals scoped variable will get passed to the included jade template. But the both files must be in jade syntax format not raw HTML if you want to do this.
Jade 确实允许服务器端包含 HTML 块,并且任何本地范围的变量都将传递给包含的 Jade 模板。但是如果你想这样做,这两个文件必须是 jade 语法格式而不是原始 HTML。
Any variable you would like to pass can just be added to the locals object.
您想传递的任何变量都可以添加到 locals 对象中。

