1

我正在使用 Handlebars.js,目前我所有的模板都位于脚本标签中,这些标签位于 .html 文件中,其中包含许多其他模板,也在脚本标签中。

<script type="text/template" id="template-1">
  <div>{{variable}}</div>
</script>

<script type="text/template" id="template-2">
  <div>{{variable}}</div>
</script>

<script type="text/template" id="template-3">
  <div>{{variable}}</div>
</script>

...

然后我将此文件作为部分文件包含在服务器端。

这有以下缺点:

  1. 一堆模板被塞进 HTML 文件中。
  2. 查找给定的模板很乏味。

我正在寻找一种更好的方式来组织我的模板。我希望每个模板都存在于自己的文件中。例如:

/public/views/my_controller/my_action/some_template.html
/public/views/my_controller/my_action/some_other_template.html
/public/views/my_controller/my_other_action/another_template.html
/public/views/my_controller/my_other_action/yet_another_template.html
/public/views/shared/my_shared_template.html

然后在我的视图顶部,在后端代码中,我可以在页面加载时包含这些模板,如下所示:

SomeTemplateLibrary.require(
    "/public/views/my_controller/my_action/*",
    "/public/views/shared/my_shared_template.html"
)

这将包括 /public/views/my_controller/my_action/ 中的所有模板,还包括 /public/views/shared/my_shared_template.html。

我的问题:是否有提供此或类似功能的库?或者,有没有人有任何替代的组织建议?

4

4 回答 4

4

RequireJS 是一个非常好的 AMD 风格依赖管理库。您实际上可以使用 requireJS 的“文本”插件将模板文件加载到您的 UI 组件中。将模板附加到 DOM 后,您可以使用任何 MVVM、MVC 库进行绑定,或者只使用 jQuery 事件作为您的逻辑。

我是 BoilerplateJS 的作者。BoilerplateJS 参考架构使用 requireJS 进行依赖管理。它还提供了一个参考实现来展示如何创建一个自包含的 UI 组件。自包含处理自己的视图模板、代码隐藏、css、本地化文件等。

BoilerplateJS UI 组件中的文件

在boilerplateJS 主页的“UI 组件”下有更多信息可用。

http://boilerplatejs.org/

于 2012-08-17T09:56:58.897 回答
2

我最终使用了 RequireJS,这几乎让我可以做到这一点。请参阅http://aaronhardy.com/javascript/javascript-architecture-requirejs-dependency-management/

于 2012-06-07T16:51:47.460 回答
2

我使用模板加载器,它在第一次需要时使用 ajax 加载模板,并将其缓存在本地以供将来请求。我还使用调试变量来确保在开发时不会缓存模板:

var template_loader = {
    templates_cache : {},
    load_template : function load_template (params, callback) {
        var template;
        if (this.templates_cache[params.url]){
            callback(this.templates_cache[params.url]);
        }
        else{
            if (debug){
                params.url = params.url + '?t=' + new Date().getTime(), //add timestamp for dev (avoid caching)
                console.log('avoid caching url in template loader...');
            }
            $.ajax({
                url: params.url,
                success: function(data) {
                    template  = Handlebars.compile(data);
                    if (params.cache){
                        this.templates_cache[params.url] =  template;
                    }
                    callback(template);
                }
            });
        }
    }
};

模板加载如下:

template_loader.load_template({url: '/templates/mytemplate.handlebars'}, function (template){
  var template_data = {}; //get your data
  $('#holder').html(template(template_data)); //render
})
于 2012-07-17T22:51:01.070 回答
0

我为此目的编写了这个方便的小 jquery 插件。

https://github.com/cultofmetatron/handlebar-helper

于 2013-03-27T07:31:02.533 回答