将HTML模板文件合并为一个JS文件

7
  1. 我有HTML模板文件(underscore模板语法)
  2. 这些文件以HTML格式保存,因此易于编辑(IDE语法高亮)
  3. 我不想使用ajax获取它们,而是将它们全部合并并包含在一个js文件中。
  4. 作为我的任务运行器,我想使用GULP以某种方式将所有HTML组合成类似于以下内容的javascript文件,该文件可以包含在我的构建过程中:

template_file_name是HTML文件名。

var templates = {
   template_file_name : '...template HTML string...',
   template_file_name2 : '...template HTML string...',
   template_file_name3 : '...template HTML string...'
}

我不太知道如何处理这个问题,以及如何从所有文件中创建这样的文本。是的,我可以将每个单独的文件转换为字符串,但是如何将其放入对象中呢?


更新 - 15年10月25日 - ES6模块:

对于那些想要将您的模板作为ES6模块的人,我创建了gulp-file-contents-to-modules

演示输出:

export var file_name = "This is bar.";
export var file_name2 = "This is foo.\r\n";
export var my-folder__file_name = "This is baz.\r\n";

所有与使用gulp合并模板文件相关的NPM包:

  1. gulp-file-contents-to-keys
  2. gulp-file-contents-to-modules
  3. gulp-template-compile-es6

这些包都可以帮助你使用gulp合并模板文件。
3个回答

2
我找到了这个完美的工具,它正好能做我想要的事情:

https://www.npmjs.org/package/gulp-template-compile

用法(就像):
gulp.task('templates', function () {
    gulp.src('./views/templates/**/*.html')
        .pipe(template()) // converts html to JS
        .pipe(concat('templates.js'))
        .pipe(gulp.dest('./js/dist/'))
});

然后你可以使用window.JST访问键/值对象。这些值是函数(我不知道为什么,但就是这样)。

更新-2015年8月21日

我决定使用gulp-file-contents-to-json,这是从文件内容生成JSON最简单的方法。

更新-2016年7月19日

我创建了3个NPM包(对某些人可能很方便):

  1. https://www.npmjs.com/package/gulp-file-contents-to-keys
  2. https://www.npmjs.com/package/gulp-file-contents-to-modules
  3. https://www.npmjs.com/package/gulp-template-compile-es6

0

你可以使用https://www.npmjs.org/package/gulp-html-to-json

它具有各种功能,非常易于使用。它将生成您所需的精确输出。

var templates = {
   template_file_name : '...template HTML string...',
   template_file_name2 : '...template HTML string...',
   template_file_name3 : '...template HTML string...'
}

如果您使用 angularjs,它还具有 angulartemplateCache 生成器。


谢谢,我会去看看。(顺便说一句,我讨厌AngularJS) - vsync
目前它无法工作(输出为空),我已通知存储库所有者。 - vsync

0

我刚刚发现的另一个工具,适用于所有handlebars.js用户的是gulp-handlebars

https://www.npmjs.com/package/gulp-handlebars

https://github.com/lazd/gulp-handlebars

在根据我的需求调整示例 gulp 任务后,我能够将 template.js 包含在我的 index.html 中,并通过 Handlebars 包装器访问每个单独的模板,方法是使用 Template.[filename]()

例如,Template.cart(data); 返回填充了所有数据的 HTML 字符串。


我认为这样的工具不应该关心它所接收到的文件。你给它文件,它会创建一个JavaScript文件,其中变量(文件名)等于该文件的内容(字符串)。就是这样。 - vsync
我同意。但是 - 它确实存在,我已经尝试过了,所以这是一个可能的解决方案。我也会尝试你建议的那个。 - ProblemsOfSumit
@vsync 显然,你链接的工具也很在意它所接收的文件。 - ProblemsOfSumit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接