使用Handlebars.js将html文件包含到另一个html文件中

在PHP中,将文件包含在另一个文件中很容易,以避免使用include关键字重复使用代码。 在使用Handlebars.JS的Node.JS中是否有类似的解决scheme?

从你的问题,这听起来像你正在寻找把手部分 。 例如,查看https://github.com/donpark/hbs/tree/master/examples/partial

总之,你会看到如下的东西:

index.hbs:

 <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Your Website</title> </head> <body> {{> header}} </body> </html> 

其中{{> header}}引用了header.hbs部分。

如果您不希望find其他方式将另一个html导入另一个html而不是Handlebars,请忽略下面的答案!

所以,而不是把手,你也可以使用液体模板引擎 ! 它很容易使用,也可以让你导入另一个HTML到另一个。

如果你也使用Gulp,你可以考虑使用液化 。 首先安装它: $ npm install --save-dev gulp-liquify 。 然后在你的gulpfile.js中使用它:

 gulp.task('html', function() { gulp.src('src/*.html') .pipe(liquify({}, {base:'./src/templates/'})) // NOTE: First argument of the liquify plugin is the locals(variables that can be used inside of the liquid template engine), For example: {name:'Fred'} .pipe(gulp.dest('build')); }); 

然后在你的html文件中,你可以很容易地在'./src/templates/'目录中包含任何其他的html文件! 像这样:

 <!DOCTYPE html> <html> {% include head.html %} <!-- See? I have included 'head.html' which is an html file in './src/templates/' directory --> <body> {% include header.html %} <div class="page-content"> <div class="wrapper"> Hello World! </div> </div> {% include footer.html %} </body> </html>