简体   繁体   English

通过Helper访问全局变量

[英]Access global variables through Helper

How can I access a global variable through a helper function in Handlebars.js for the purpose of localization? 如何通过Handlebars.js中的帮助器函数访问全局变量以进行本地化? Here's what I've got so far. 这是到目前为止我得到的。 The problem I'm seeing is that the parameter 'string' is undefined inside the registerHelper anonymous function. 我看到的问题是在registerHelper匿名函数中参数'string'是未定义的。

Template 模板

<span>{{resourceHelper date}}:</span>

String Resources 字符串资源

Resources = {};
Resources['date'] = "Date";

Helper Function 辅助功能

Handlebars.registerHelper('resourceHelper', function(string) {
    return Resources[string];
});

I discovered that the parameter being passed into the helper was the actual object name within the Handlebars context. 我发现传递给帮助器的参数是Handlebars上下文中的实际对象名称。 So passing date obviously didn't work, as there was no associated object in that context. 因此,传递date显然不起作用,因为在该上下文中没有关联的对象。 You can, however, pass the values as strings: 但是,您可以将值作为字符串传递:

{{resourceHelper "date"}}

This solved my problem with no other changes to the helper function required. 这样就解决了我的问题,无需对辅助函数进行其他任何更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM