gpt4 book ai didi

javascript - 打包基于 Handlebars 的小部件 : javascript and html

转载 作者:行者123 更新时间:2023-11-28 06:52:13 24 4
gpt4 key购买 nike

我对此还比较陌生,所以如果我遗漏了一些明显的要点,请原谅......

我想使用 Handlebars 创建一个可重用的小部件,为简单起见,让我们考虑一个用户表:

<script type="text/x-handlebars-template" id="temp1">
<table>
{{#users}}
<tr><td>{{name}}</td><td>{{email}}</td></tr>
{{/users}}
</table>
</script>

<script>
var template=Handlebars.compile($("#temp1").html());
function renderUsersTable(users, divId){
$("#"+divId).html(template(users:users));
}
<script>

这可行,但我只能将其与嵌入到我的业务页面中的模板脚本 (text/x-handlebars-template) 配合使用。这是不可重复使用的:如果我在另一个页面上需要它,我需要复制粘贴。我考虑过将模板引用到 JavaScript 字符串变量中,但这很丑陋,尤其是因为我真正的 html 非常大。

是否有更好的做法,可以将 Handlebars 模板分离到专用文件中,并根据需要包含到不同的页面中?

非常感谢

最佳答案

是的。一种方法是使用 gulp 任务来编译所有模板。下面的示例从一个目录中获取所有单独的 Handlebars 文件,并将它们作为模板放入一个 javascript 文件 hb_templates.js 中。每个模板都有其来源文件的名称。对于您的示例,您可以将模板放入users.handlebars中。然后将生成的 hb_templates.js 包含在生产网页中的 Handlebars.js 后面。

gulp.task('handlebars', function() {
gulp.src('./app/views/*.handlebars')
.pipe(htmlmin({
collapseWhitespace: true
}))
.pipe(handlebars())
.pipe(wrap(function(data) {
var filename = data.file.history[0].split('\\').pop().split('.')[0];
return "Handlebars.templates." + filename + "=Handlebars.template(<%= contents %>)";
}))
.pipe(concat('hb_templates.js'))
.pipe(gulp.dest('./app/scripts/'));
});

你像这样使用模板;

$("#"+divId).html(Handlebars.templates.user(users:users));

由于 Handlebars 中的部分只是模板,因此您可以在其他模板文件中使用这些模板,如下所示

<div>
{{> user}}
</div>

像这样加载 hb_templates.js 后,只需将它们注册为部分即可;

handlebars.registerPartial('user', handlebars.templates.user);

该示例在 nodejs 中为 gulp 使用了以下依赖项

{
"gulp": "3.9.0",
"gulp-concat": "2.6.0",
"gulp-handlebars": "4.0.0",
"gulp-htmlmin": "1.1.3",
"gulp-wrap": "0.11.0",
"handlebars": "3.0.3",
}

关于javascript - 打包基于 Handlebars 的小部件 : javascript and html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32863220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com