javascript 将任意参数传递给把手助手?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18903003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:38:08  来源:igfitidea点击:

Passing arbitrary arguments to handlebars helpers?

javascriptember.jsinternationalizationhandlebars.js

提问by Alexandros K

sorry if this has been asked a million times before but I can't seem to find a satisfactory answer anywhere.

对不起,如果这已经被问了一百万次,但我似乎无法在任何地方找到满意的答案。

I'm trying to build a handlebars helper to tie into my i18n library and I need it to accept any number of named arguments as follows:

我正在尝试构建一个把手助手来绑定到我的 i18n 库中,我需要它接受任意数量的命名参数,如下所示:

{{i18n yml.text.definition count=2 name="Alex" ... param="hello}}

which will translate to a call like this:

这将转化为这样的调用:

i18n.t("yml.text.definition", { count: 2, name: "Alex", ... param: "hello"})

Is this possible, or am I totally out of my tree?

这是可能的,还是我完全脱离了我的树?

采纳答案by Marcio Junior

Give the following helper:

提供以下帮手:

{{myHelper "foo" this ... key=value ...}}

You can get the data with the following declaration:

您可以使用以下声明获取数据:

Ember.Handlebars.helper('name', function(param1, param2, options) {
  param1 // The string "foo"
  param2 // some object in that context
  options.hash // { key: value }
});

Each parameter of the function is the parameter passed in {{myHelper param1 param2}}. But the remaining will be an object with some special/private information. With that object you retrieve the key=value information using the hash object.

函数的每个参数都是在{{myHelper param1 param2}}中传入的参数。但剩下的将是一个带有一些特殊/私人信息的对象。通过该对象,您可以使用哈希对象检索 key=value 信息。

If the paramter supplied to the helper is quoted, like "param1", the string is returned, otherwise it's resolved to some object in that context.

如果提供给帮助程序的参数被引用,如“param1”,则返回字符串,否则将其解析为该上下文中的某个对象。

In your case you will need:

在您的情况下,您将需要:

Ember.Handlebars.helper('i18n', function(property, options) {        
    var hash = options.hash;    
    return 'i18n.t(' + property + ', { count: ' + hash.count + ', name: ' + hash.name + ', param: ' + hash.param + '})';
});

Here is a jsfiddle with this working http://jsfiddle.net/marciojunior/64Uvs/

这是一个 jsfiddle 与这个工作http://jsfiddle.net/marciojunior/64Uvs/

I hope it helps

我希望它有帮助

回答by chopper

Try this:

试试这个:

Ember.Handlebars.registerBoundHelper('i18n', function(context, block) {
  return i18n.t(context, { count: block.hash.count, name: block.hash.name, ... param: block.hash.param}); 
});