javascript - 是否可以通过模板内的 JS 访问发送到 handlebars 的数据?

标签 javascript jquery handlebars.js

假设我从外部 Handlebars 模板(通过 AJAX)生成内容

$.ajax({
    url: path,
    dataType: 'html',
    success: function(data) {
        source    = data;
        template  = Handlebars.compile(source);
        //execute the callback if passed
        if (callback) callback(template);
    }
});

现在在我的 template.handlebars 中,我使用标签 {{this}} 等输出我发送的数据。 但我还在模板底部包含了一些仅适用于该模板的 javascript(效果很好)。但是我需要在 javascript 中访问发送到模板的一些数据,这可能吗?

一个非常愚蠢的例子,我知道它不起作用,但应该解释我在做什么,以防它不清楚。所以这可能是我的 template.handlebars 文件的示例:

<h1>{{question}}</h1>

<script>
//want to access the data sent to template in the JS included
(function($) { //wrap to local scope
    $(document).ready(function() {
        //this doesn't work ofcourse.. but should explain what I'm after
        var question = {{question}};
        console.log(question)
    });
})(jQuery);

关于如何做到这一点有什么想法吗?对我来说,以这种方式包含仅适用于特定模板的 JS 感觉很干净。

最佳答案

当您编译 Handlebars 模板时,它们只会通过替换 {{expression}} 返回给您字符串。

所以你必须处理每种数据类型。对于字符串,请像这样使用。

var question = "{{question}}";

整数应该没有问题。它们可以像这样直接放置。

var question = {{question}};

我已经为对象工作过。您可以为对象和数组调用助手。

引用这个stackoverflow post处理对象。

关于javascript - 是否可以通过模板内的 JS 访问发送到 handlebars 的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19247150/

相关文章:

Javascript |按钮未使用 .innerHTML 提交表单

javascript - 在 javascript 中挑选出特定的单独控件

javascript - 单击本身更改按钮背景颜色

javascript - 如何扩展 EmberJS handlebars 输入助手以支持没有值的属性?

javascript - 如何访问 Handlebars 中的 URL 参数?

javascript - 使用 Angular 生成动态引导菜单

Javascript循环创建多个相互附加的div

jquery - jqGrid 中 setCell 后 editRow 不起作用

javascript - 如何将 float div 的高度设置为其邻居的相同高度

javascript - 使用handlebars.js 登录状态相关菜单