[英]How do I add a rails controller variable to javascript file console.log?
[英]How do I add console.log() JavaScript logic inside of a Handlebars template?
我正在构建一个新的Meteor应用程序,我无法弄清楚如何在每个循环之前使用Handlebars添加JavaScript逻辑来运行console.log()
。 在骨干中我会做, <% console.log(data); %>
<% console.log(data); %>
来测试数据是否正在传入。
我不知道如何使用Meteor和Handlebars这样做,我在他们的网站上找不到解决方案。
在项目中的一个客户端加载的JavaScript文件中创建Handlebars帮助器:
Template.registerHelper("log", function(something) {
console.log(something);
});
然后在模板中调用它:
{{log someVariable}}
您可以使用{{log this}}
来记录当前上下文。
(请注意,在版本0.8之前的Meteor中,或者在Meteor应用程序之外的纯手柄中,将Template.registerHelper
替换为Handlebars.registerHelper
。)
Handlebars v3现在有一个内置的日志助手。 您可以从模板中登录控制台
{{log this}}
您可以像这样设置日志记录级别
Handlebars.logger.level = 0; // for DEBUG
我发现这个助手非常有用
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}}
打印出那个价值
我这样做,
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>
我总是使用以下帮助器:它记录数据并添加一个可选的断点。 这样你可以在浏览器调试器中检查当前的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 '';
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.