【问题标题】:Backbone.js and Handlebars - Using grunt-contrib-handlebarsBackbone.js 和 Handlebars - 使用 grunt-contrib-handlebars
【发布时间】:2013-02-08 23:30:25
【问题描述】:

我只是想知道是否有人在骨干项目中使用过这个插件。

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

所以我希望我可以使用节点选项来要求本地模板并渲染到它,然后附加到我的索引文件上的#id(我将在最后整理)。

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

public
   |_ coffee
      |_views
        |_card
           |_list
              index.coffee
              template.hbs
              template.js

作为参考,我的 grunt 文件如下所示:

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) 中,我希望像这样需要车把模板:

class CardList extends Backbone.View
    template: require('./template')


    … 
    do some other shiz
    …


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

渲染这个是在检查器中吐出这个错误:

Uncaught [object Object]

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

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

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

感谢任何帮助。

谢谢

【问题讨论】:

标签: backbone.js handlebars.js gruntjs


【解决方案1】:

您也许可以通过building the files object dynamically 实现这一目标。

也许是这样,虽然我不确定cwd 是否支持通配模式。我也不确定dest 是否相对于cwd。如果不是这种情况,这将不起作用,但值得一试。

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'
  }
},

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 2012-06-30
      • 2012-07-23
      • 2013-07-16
      • 1970-01-01
      • 2013-07-10
      • 2015-06-26
      • 1970-01-01
      相关资源
      最近更新 更多