Skip to content
This repository
Browse code

* Added support for hash arguments as optional parameters for handleb…

…ars templates
  • Loading branch information...
commit a8637a18642abd44e2095912ce8e172520e4fb79 1 parent 3900a2b
authored December 21, 2012
37  lib/template/adapters/handlebars.js
@@ -49,7 +49,7 @@ Handlebars.prototype.registerHelper = function (name, helper) {
49 49
     return false;
50 50
   }
51 51
 
52  
-  this.engine.registerHelper(name, helper);
  52
+  this.engine.registerHelper(name, this.wrapOptions(helper));
53 53
 };
54 54
 
55 55
 Handlebars.prototype.registerHelpers = function (helpers) {
@@ -62,4 +62,39 @@ Handlebars.prototype.registerHelpers = function (helpers) {
62 62
   }
63 63
 };
64 64
 
  65
+/*
  66
+ * In erj we can simple call function passing options hash
  67
+ * as argument in template, but for for handlebars it's impossible,
  68
+ * cause object hash is not mustache expression
  69
+ *
  70
+ * We can use optional has arguments in handlerbars for this,
  71
+ * but will be passed inside wrapped option object {hash : { foo : 'bar', baz : 'bla' }}
  72
+ * and template helpers in /template/helpers like urlFor
  73
+ * is not intended to work with this. So we just unpack options and pass them
  74
+ * to regular helper function and we can keep one set helpers with optional arguments
  75
+ * for handlebars and other engines
  76
+ */
  77
+
  78
+Handlebars.prototype.wrapOptions = function (helper) {
  79
+  return function() {
  80
+    var argsLen = arguments.length,
  81
+      options = argsLen ? arguments[argsLen - 1] : null,
  82
+      i = 0 , newArgs;
  83
+
  84
+    if (options && options.hash) {
  85
+      newArgs = [];
  86
+
  87
+      for (;i<argsLen - 1; i++) {
  88
+        newArgs.push(arguments[i]);
  89
+      }
  90
+
  91
+      newArgs.push(options.hash);
  92
+      return helper.apply(this, newArgs);
  93
+    }
  94
+    else {
  95
+      return helper.apply(this, arguments);
  96
+    }
  97
+  }
  98
+}
  99
+
65 100
 module.exports = Handlebars;
13  test/templates/engines/handlebars_mustache.js
@@ -80,6 +80,19 @@ tests = {
80 80
     var html = '<p>foo</p>',
81 81
       str = '<p>{{#items}}{{foo}}{{/items}}</p>';
82 82
     assert.equal(html, render(str, {items: [{foo: 'foo'}]}));
  83
+  },
  84
+
  85
+  'test hash arguments' : function () {
  86
+    var html = 'foobar.com/main/index'
  87
+      , tpl = "{{url host='foobar.com' controller='main' action='index'}}"
  88
+      , helper = function(options) {
  89
+        console.log(options);
  90
+        return options.host + '/' + options.controller + '/' + options.action
  91
+      }
  92
+
  93
+    var adapter = new Adapter({engine: 'handlebars', template: tpl});
  94
+    adapter.registerHelper('url', helper);
  95
+    assert.equal(html, adapter.render());
83 96
   }
84 97
 
85 98
 };

0 notes on commit a8637a1

Please sign in to comment.
Something went wrong with that request. Please try again.