Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arbitrary arguments to handlebars helpers?

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 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?

like image 563
Alexandros K Avatar asked Sep 19 '13 19:09

Alexandros K


1 Answers

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.

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.

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/

I hope it helps

like image 118
Marcio Junior Avatar answered Sep 17 '22 18:09

Marcio Junior