From c9970200a04a8629b5e9b1ed3c540d391ab00f26 Mon Sep 17 00:00:00 2001 From: Nils Knappmeier Date: Sun, 29 Jan 2017 07:11:01 +0100 Subject: [PATCH] Fix compiler-api example (#1303) Closes #1302 While trying to answer #1302, I noticed that the compiler-api example did not work in (because `nameLookup` is actually at the prototype). This example has a jsfiddle that proves it is working. It does not provide an solve the exact problem of the reporter, but it answers the question. --- docs/compiler-api.md | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/docs/compiler-api.md b/docs/compiler-api.md index c9d2e937..a0478dea 100644 --- a/docs/compiler-api.md +++ b/docs/compiler-api.md @@ -296,21 +296,36 @@ The `Handlebars.JavaScriptCompiler` object has a number of methods that may be c - `initializeBuffer()` Allows for buffers other than the default string buffer to be used. Generally needs to be paired with a custom `appendToBuffer` implementation. +### Example for the compiler api. + +This example changes all lookups of properties are performed by a helper (`lookupLowerCase`) which looks for `test` if `{{Test}}` occurs in the template. This is just to illustrate how compiler behavior can be change. + +There is also [a jsfiddle with this code](https://jsfiddle.net/9D88g/85/) if you want to play around with it. + + ```javascript function MyCompiler() { Handlebars.JavaScriptCompiler.apply(this, arguments); } -MyCompiler.prototype = Object.create(Handlebars.JavaScriptCompiler); +MyCompiler.prototype = new Handlebars.JavaScriptCompiler(); -MyCompiler.nameLookup = function(parent, name, type) { - if (type === 'partial') { - return 'MyPartialList[' + JSON.stringify(name) ']'; +MyCompiler.prototype.nameLookup = function(parent, name, type) { + if (type === 'context') { + return this.source.functionCall('helpers.lookupLowerCase', '', [parent, JSON.stringify(name)]) } else { return Handlebars.JavaScriptCompiler.prototype.nameLookup.call(this, parent, name, type); } -}; +} var env = Handlebars.create(); +env.registerHelper('lookupLowerCase', function(parent, name) { + return parent[name.toLowerCase()] +}) + env.JavaScriptCompiler = MyCompiler; -env.compile('my template'); + +var template = env.compile('{{#each Test}}{{.}} {{/each}}'); +console.log(template({ + test: [ "a","b","c"] +})); ```