Handlebars.js错过了JSON数据

时间:2012-03-26 07:25:39

标签: requirejs handlebars.js

我有一个由Require.js加载的模板文件:

主要-app.js

define([
        'backboneLoader',
        'handlebars',
        'text!templates/main.html',
        'text!appdata.json'
    ],
    function(
        Backbone,
        Handlebars,
        MainTemplate,
        AppData
    ) {
        "use strict";

        return Backbone.View.extend({
            initialize : function() {
                this.render();
            },

            render : function() {
                var template = Handlebars.compile(MainTemplate);
                var output = template(AppData);
                this.$el.append(output);
                console.log("appData:\n" + AppData);
                console.log("MainTemplate:\n" + MainTemplate);
                console.log("Output:\n" + output);
                    //smth extra
                return this;
            }
        });
    }
);

MainTemplate(main.html)

<ul>
    <li><b>Version:</b> {{version}}</li>
    <li><b>Author:</b> {{author}}</li>
</ul>

AppData(appdata.json)

{version: "0.0.1", author: "John Doe"}

输出:

<ul>
     <li><b>Version:</b></li>
     <li><b>Author:</b></li>
</ul>

预期输出:

<ul>
        <li><b>Version:</b> 0.0.1</li>
        <li><b>Author:</b> John Doe</li>
</ul>

任何想法我做错了什么?谢谢!

UPD: 问题解决了。这里更新了 main-app.js:

define([
        'backboneLoader',
        'handlebars',
        'text!templates/main.html!strip',
        'text!appdata.json'
    ],
    function(
        Backbone,
        Handlebars,
        mainTemplate,
        appData
    ) {
        "use strict";

        return Backbone.View.extend({
            initialize : function() {
                this.render();
            },

            render : function() {
                var template = Handlebars.compile(mainTemplate);
                var output = template(eval("(" + appData + ")")); //Object is expected by template(), not JSON.
                this.$el.append(output);
                console.log("appData:\n" + appData);
                console.log("template:\n" + mainTemplate);
                console.log("Output:\n" + output);
                    //smth extra
                return this;
            }
        });
    }
);

2 个答案:

答案 0 :(得分:1)

问题是AppData是一个JSON字符串,而不是一个实际的Object。只需更改:

var output = template(AppData);

var output = template(JSON.parse(AppData));

您可能需要添加json2.js来为旧浏览器添加JSON支持(&lt; = IE7)。

答案 1 :(得分:0)

这是模板函数的jsFiddle repro,模板转换似乎有效,问题可能就在文本中!函数在require.js代码中,尝试调试文本!功能

在加载模板时,还要尝试添加!strip函数:'text!templates / main.html!strip',

文档建议:For HTML/XML/SVG files, there is another option. You can pass !strip, which strips XML declarations so that external SVG and XML documents can be added to a document without worry.