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

Packaging a Handlebars-based widget: javascript and html

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

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

<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。然后在您的生产网页中的 Handlebars.js 之后包含生成的 hb_templates.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",
}