如何在Handlebars模板中添加console.log()JavaScript逻辑?

时间:2013-07-06 04:46:29

标签: javascript templates meteor handlebars.js meteorite

我正在构建一个新的Meteor应用程序,我无法弄清楚如何在每次循环之前使用Handlebars添加JavaScript逻辑来运行console.log()。在骨干中,我会做<% console.log(data); %>来测试数据是否被传入 我不知道如何使用Meteor和Handlebars这样做,我在他们的网站上找不到解决方案。

5 个答案:

答案 0 :(得分:42)

在项目中的一个客户端加载的JavaScript文件中创建一个Handlebars帮助器:

Template.registerHelper("log", function(something) {
  console.log(something);
});

然后在模板中调用它:

{{log someVariable}}

您只需使用{{log this}}

记录当前上下文

(请注意,在版本0.8之前的Meteor中,或在Meteor应用程序之外的纯手柄中,将Template.registerHelper替换为Handlebars.registerHelper。)

答案 1 :(得分:19)

Handlebars v3现在有一个内置的日志助手。您可以从模板

中登录控制台
{{log  this}}

您可以像这样设置日志记录级别

Handlebars.logger.level = 0; // for DEBUG

答案 2 :(得分:13)

我发现这个助手非常有用

Handlebars.registerHelper("debug", function(optionalValue) {
    console.log("Current Context");
    console.log("====================");
    console.log(this);
    if (optionalValue) {
        console.log("Value");
        console.log("====================");
        console.log(optionalValue);
    }
});

然后你可以用两种方式使用它

只是一个简单的

{{debug}}

将打印出当前上下文

或检查单个值

{{debug val}}

只打印出该值

答案 3 :(得分:2)

我这样做,

Handlebars.registerHelper('log', function(content) {
  console.log(content.fn(this));
  return '';
});

允许我使用我坐在里面的模板系统编写调试器块。所以我可以给它一个块,它将解析内容,但只是将它发送到console.log。

{{#log}} title is {{title}} {{/log}}

我也这样做

$('script[type="text/x-handlebars-template"]').each(function(){
    Handlebars.registerPartial(this.id,$(this).html());
});

这使得我的所有模板都可以作为部分模板使用,这使我可以将模板干燥成可重复使用的功能块,而无需编辑模板本身以外的任何其他模块。

所以我现在可以做像

这样的事情
{{#log}}Attribute listing {{>Attributes}}{{log}}

<script id="Attributes" type="text/x-handlebars-template">
{{#each attributes}} 
    {{@key}}={{this}} 
{{/each}}
</script>

答案 4 :(得分:1)

我总是使用以下帮助程序:它记录数据并添加可选的断点。这样,您可以在浏览器调试器中检查当前的Handlebars上下文; - )

https://gist.github.com/elgervb/5c38c8d70870f92ef6338a291edf88e9

上找到
/**
* Register a debug helper for Handlebars to be able to log data or inspect data in the browser console
* 
* Usage: 
*   {{debug someObj.data}} => logs someObj.data to the console
*   {{debug someObj.data true}} => logs someObj.data to the console and stops at a debugger point
* 
* Source: https://gist.github.com/elgervb/5c38c8d70870f92ef6338a291edf88e9
* 
* @param {any} the data to log to console
* @param {boolean} whether or not to set a breakpoint to inspect current state in debugger
*/
Handlebars.registerHelper( 'debug', function( data, breakpoint ) {
    console.log(data);
    if (breakpoint === true) {   
        debugger;
    }
    return '';
});
相关问题