Nodejs Include Other Views?

2019-09-15 23:37发布

I am using html views. Is there a something like this? :

{{include head.html}}
index
</body>
</html>

4条回答
迷人小祖宗
2楼-- · 2019-09-15 23:59

What you are looking for is a templating engine, since you mentioned the {{ }}tags I am assuming you are using Hogan.js aka moustache(the javascript version).

The documentation can be found here and what you are specifically looking for is the partials section.

Please note, the default express app(if you select hogan) comes installed with the hjs module which does not support partials, you will need to install the hogan-express module and replace them.

A partial looks like so:

{{> head}}
index
</body>
</html>

Partials are sent from a get or post object like so:

res.render('index.html', {
    partials: {
        head: 'partials/head.html'
    }
});
查看更多
我想做一个坏孩纸
3楼-- · 2019-09-16 00:17

I found the solution. server.js

var hbs = require('hbs');
app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
hbs.registerPartials(__dirname + '/views/'); <-------- include folder

index.html Index.html includes head.html like this:

{{> head}}
index
</body>
</html>
查看更多
老娘就宠你
4楼-- · 2019-09-16 00:18

If you do not want to use ejs or jade etc then you could do it with jquery. Put this code in index.html

<html>
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script> 
  $(function(){
     $("#header").load("header.html"); 
     $("#footer").load("footer.html"); 
});
</script> 
</head>
<body>
<div id="header"></div>
    <!--Remaining section-->
<div id="footer"></div>
</body>
</html>
查看更多
ら.Afraid
5楼-- · 2019-09-16 00:20

You are looking for a template engine for nodejs?

For example check here: http://node-modules.com/search?q=template+engine

查看更多
登录 后发表回答