在我目前的项目中,我的工作仅限于html和css( HTML skinning )。有许多页面具有重复的部分,如页眉,页脚,共享链接等。
我不想在每个页面中反复重复这个常见部分。我希望这些重复的部分可以使用gulp或任何其他任务运行程序以某种方式调用。
例如这样的东西(使用lodash )
<!Doctype html>
<html>
<%= _.template(templates['head'])() %>
<body>
<%= _.template(templates['header'])() %>
<!-- some unique content here -->
<%= _.template(templates['footer'])() %>
</body>
</html>
然后使用gulp-template在每个页面中呈现它。我更喜欢lodash,因为我已经使用过它。
正如您所看到的,我假设如果我以某种方式将重复部分保留在javascript对象(名称为templates
)中,我可以在一个行代码中调用它。然后,如果我在该重复部分中更改某些内容,则会在所有页面中进行更改。
为了实现这一点,首先我需要生成javascript对象,其中重复的html为字符串。
有人可以告诉我怎么做吗?或者有更好的方法吗?
答案 0 :(得分:3)
您可以使用Jade - 节点模板引擎
它为include外部玉文件提供了选项,其中允许您将一个玉文件的内容插入另一个
doctype html
html
include ./includes/head.jade
body
h1 My Site
p Welcome to my super lame site.
include ./includes/foot.jade
//- includes/head.jade
title My Site
script(src='/javascripts/jquery.js')
script(src='/javascripts/app.js')
//- includes/foot.jade
#footer
p Copyright (c) foobar
<!doctype html>
<html>
<head>
<title>My Site</title>
<script src='/javascripts/jquery.js'></script>
<script src='/javascripts/app.js'></script>
</head>
<body>
<h1>My Site</h1>
<p>Welcome to my super lame site.</p>
<div id="footer">
<p>Copyright (c) foobar</p>
</div>
</body>
</html>
答案 1 :(得分:0)
每当我在Google上搜索“预编译模板”时,我最终都会将所有HTML模板文件合并到一个单独的js文件中。但在我的情况下,我一直在寻找一种方法来完全在系统上编译模板,而不支持“所有模板编译的js文件”。 (所以,我正在寻找预渲染 HTML 的解决方案)
我找到了这个非常棒的模板引擎Nunjucks,它允许我在与gulp一起使用时将HTML模板编译为独立的HTML页面。
选中此项gulp-nunjucks-render。通过将其与gulp一起使用,我可以将.html
个文件的一部分包含到其他.html
文件中。这是代码(假设您安装了nodejs和gulp ):
var gulp = require('gulp');
var nunjucksRender = require('gulp-nunjucks-render');
gulp.task('default', function () {
nunjucksRender.nunjucks.configure(['templates/'], { watch: false });
return gulp.src('templates/!(_)*.html')
.pipe(nunjucksRender({
css_path: "../assets/css/",
js_path: "../assets/js/",
img_path: "../assets/images/"
}))
.pipe(gulp.dest('html'));
});
gulp.task('watch', function () {
gulp.watch(['templates/*.html'], ['default']);
});
在上面的代码中,我将HTML模板保存在templates
文件夹中,并使用上面的gulp代码,我在html
文件夹中生成新的HTML。上面的代码不会生成带有_
前缀的文件。 (类似于sass )
以及稍后的命令提示符:
gulp watch // Watches the files for changes continuously --> OWNING :D
以下是一个例子:
<!-- // Index.html -->
<!DOCTYPE html>
<html>
{% include "_head.html" %}
<body>
{% include "_content.html" %}
{% include "_footer.html" %}
</body>
</html>
呈现给:
<!DOCTYPE html>
<html>
<head>
<title>Website title</title>
<link rel="Stylesheet" href="../assets/jcss/main.css" type="text/css"/>
</head>
<body>
<div class="page">
<!-- content here -->
</div>
<div class="footer">
<!-- footer content here -->
</div>
</body>
</html>