关于handlebars.js:Backbone.js和Handlebars-使用grunt-contrib-handlebars

Backbone.js and Handlebars - Using grunt-contrib-handlebars

我只是想知道是否有人在Backbone 项目中使用过此插件。

我不想将所有脚本模板标签都放在一个索引文件中,而是希望将模板与需要它们的视图存放在同一目录中。

所以我希望我可以使用node选项来要求本地模板并呈现给它,然后附加到索引文件上的#id(我将对其进行整理)。

所以基本上,我在主干视图index.coffee旁边有我的车把模板(template.hbs)及其编译的js(template.js)。

1
2
3
4
5
6
7
8
public
   |_ coffee
      |_views
        |_card
           |_list
              index.coffee
              template.hbs
              template.js

仅供参考,我的咕unt声文件如下所示:

1
2
3
4
5
6
7
8
9
10
11
handlebars: {
      compile: {
        options: {
          namespace: 'MyApp.Templates',
          node: true
        },
        files: {
         "public/coffee/views/card/list/template.js":"public/coffee/views/card/list/template.hbs"
        }
      }
    },

在我的主干视图(index.coffee)中,我希望像这样需要把手模板:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class CardList extends Backbone.View
    template: require('./template')


    a€|
    do some other shiz
    a€|


render: =>
    template = Handlebars.compile($(this.template).html())
    html = template
        model: this.model
    $(this.el).html(html)

呈现此结果将在检查器中吐出此错误:

1
2
3
Uncaught [object Object]

> template = handlebars.compile($(this.template).html());

我显然不知道自己在做什么,所以我希望有人可以阐明如何正确使用此插件。

我正在使用grunt-contrib-handlebars v0.3.5

我们将不胜感激。

谢谢


您可能可以通过动态构建文件对象来实现。

也许有点像这样,尽管我不确定cwd是否支持globbing模式。我也不确定dest是否相对于cwd。如果不是这种情况,则将无法正常工作,但值得一试。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
handlebars: {
  dist: {
    options: {
      namespace: 'MyApp.Templates',
      node: true
    },
    // Glob for a directory of files, builds the files object, then map each
    // one to a new destination file.
    expand: true,
    cwd: './public/coffee/views/*',
    src: '**/*.hbs',
    dest: './',
    ext: '.js'
  }
},

查看要包含的template.js文件。 grunt-comtrib-handlbars应该已经为您预编译为Javascript函数,因此不再需要调用Handlebars.compile。您可以只删除该模板= Handlebars.compile行。