Compare commits

...

30 Commits

Author SHA1 Message Date
kpdecker efad61b1b7 v2.0.0-alpha.4 2014-05-19 23:15:50 -05:00
kpdecker 2a20976e6a Update release notes 2014-05-19 23:15:18 -05:00
kpdecker 3638874ddc Expose setup wrappers for compiled templates 2014-05-19 23:08:34 -05:00
kpdecker f419838362 v2.0.0-alpha.3 2014-05-19 22:29:25 -05:00
kpdecker 8ee73b9d13 Update release notes 2014-05-19 22:29:08 -05:00
kpdecker 3dcc49927b Drop travis 0.8 build support
The date-now dependency has dropped support and that version is sufficiently old that we shouldn’t have any issues not testing against it anymore.
2014-05-19 22:02:57 -05:00
Kevin Decker e10eb537ab Merge pull request #797 from tomdale/full-helper-names
Pass full helper ID to helperMissing when options are provided
2014-05-19 21:59:20 -05:00
Kevin Decker 8f09ea5f40 Merge pull request #793 from mmun/ast-tweaks
Ensure isHelper is coerced to a boolean
2014-05-19 21:56:24 -05:00
Tom Dale 72c1262394 Pass full id to helperMissing 2014-05-13 13:24:25 +01:00
Martin Muñoz 356ea1a909 Ensure isHelper is coerced to a boolean 2014-05-05 01:51:29 -04:00
kpdecker 085e5e1937 Refactor template init logic 2014-04-13 07:21:08 -05:00
kpdecker a601b24a73 Update travis exec for S3 push 2014-03-29 13:27:12 -05:00
kpdecker 04c312649b v2.0.0-alpha.2 2014-03-06 01:26:26 -06:00
kpdecker fea46dbb8c Update release notes 2014-03-06 01:26:15 -06:00
kpdecker b61c75512a Remove log in test 2014-03-05 21:11:47 -06:00
kpdecker 1da136490b Add version option to compiler
Fixes #746
2014-03-05 18:32:23 -06:00
kpdecker d55f9966b9 Update escaping in link_to example 2014-03-05 18:27:48 -06:00
Kevin Decker d33ae150cd Merge pull request #740 from SimonCropp/patch-1
Update README.markdown
2014-03-05 18:24:59 -06:00
kpdecker 8347ee2591 Temporarily kill the AWS publish CI step 2014-03-05 18:17:46 -06:00
kpdecker 55782f08c5 Fix evaluation of paths and subexprs
Fixes #743
2014-03-05 17:49:39 -06:00
kpdecker 058c0fb6ba Make JSON a requirement for the compiler.
Include the polyfill for testing under IE8 and below and document this.
2014-03-05 17:15:23 -06:00
kpdecker 10168cb0a9 Remove keyword that chokes up IE tests 2014-03-05 15:07:19 -06:00
kpdecker 66538cc7fa Drop opera tests
The Sauce implementation doesn't seem to work properly.
2014-03-05 15:03:13 -06:00
Kevin Decker 7dd64e5e92 Merge pull request #749 from jenseng/option_subexpressions_fix
properly handle multiple subexpressions in the same hash, fixes #748
2014-03-05 14:38:26 -06:00
Kevin Decker 674d07fd03 Merge pull request #756 from jenseng/mapfix
fix bug in IE<=8 (no Array::map), closes #751
2014-03-05 14:36:57 -06:00
Jon Jensen 5999baf746 fix bug in IE<=8 (no Array::map), closes #751
looks like this broke in 2812fe27

also s/this.i/var i/, since the functions that needed it were removed in
a1edab6ef
2014-03-04 22:18:50 -07:00
Kevin Decker fd5dfc861c Merge pull request #747 from Jonahss/master
updated grunt-saucelabs, failing tests revealed
2014-02-24 19:20:08 -06:00
Jon Jensen 8493822b62 properly handle multiple subexpressions in the same hash, fixes #748
push all hash params before popping any so as to avoid the last stackN var
stomping previous ones
2014-02-20 17:37:25 -06:00
jonahss c86ac60876 updated grunt-saucelabs, failing tests revealed 2014-02-18 16:14:31 -08:00
Simon Cropp c68620caf9 Update README.markdown 2014-02-15 22:05:38 +11:00
19 changed files with 718 additions and 85 deletions
+10 -17
View File
@@ -1,30 +1,23 @@
language: node_js
node_js:
- "0.8"
before_install:
- npm install -g grunt-cli
- npm install -g grunt-cli
script:
- grunt --stack travis
- grunt --stack travis
email:
on_failure: change
on_success: never
env:
global:
- S3_BUCKET_NAME=builds.handlebarsjs.com
- secure: PJaukuvkBBsSDOqbIcNSSMgb96VVEaIt/eq9GPjXPeFbSd3hXgwhwVE62LrqtJO8BaUfX+PzpiQjEl4D5/KBmvlFZ057Hqmy0zmPOT5mDZfJe8Ja5zyvTMb+KkCWN/tjAp8kawHojE04pn6jIpPdwXFnAYwPhaHbATFrmdt9fdg=
- secure: mBcGL2tnmiRujJdV/4fxrVd8E8wn6AW9IQKVcMv8tvOc7i5dOzZ39rpBKLuTMRXDtMV1LyLiuKYb1pHj1IyeadEahcLYFfGygF4LG7Yzp4NWHtRzQ7Q8LXaJV7dXDboYCFkn2a8/Rtx1YSVh/sCONf5UoRC+MUIqrj4UiHN9r3s=
- secure: ckyEe5dzjdFDjmZ6wIrhGm0CFBEnKq8c1dYptfgVV/Q5/nJFGzu8T0yTjouS/ERxzdT2H327/63VCxhFnLCRHrsh4rlW/rCy4XI3O/0TeMLgFPa4TXkO8359qZ4CB44TBb3NsJyQXNMYdJpPLTCVTMpuiqqkFFOr+6OeggR7ufA=
- secure: Nm4AgSfsgNB21kgKrF9Tl7qVZU8YYREhouQunFracTcZZh2NZ2XH5aHuSiXCj88B13Cr/jGbJKsZ4T3QS3wWYtz6lkyVOx3H3iI+TMtqhD9RM3a7A4O+4vVN8IioB2YjhEu0OKjwgX5gp+0uF+pLEi7Hpj6fupD3AbbL5uYcKg8=
matrix:
include:
- node_js: "0.10"
env:
- PUBLISH=true
- secure: pLTzghtVll9yGKJI0AaB0uI8GypfWxLTaIB0ZL8//yN3nAEIKMhf/RRilYTsn/rKj2NUa7vt2edYILi3lttOUlCBOwTc9amiRms1W8Lwr/3IdWPeBLvLuH1zNJRm2lBAwU4LBSqaOwhGaxOQr6KHTnWudhNhgOucxpZfvfI/dFw=
- secure: yERYCf7AwL11D9uMtacly/THGV8BlzsMmrt+iQVvGA3GaY6QMmfYqf6P6cCH98sH5etd1Y+1e6YrPeMjqI6lyRllT7FptoyOdHulazQe86VQN4sc0EpqMlH088kB7gGjTut9Z+X9ViooT5XEh9WA5jXEI9pXhQJNoIHkWPuwGuY=
- node_js: '0.10'
env:
- PUBLISH=true
- secure: pLTzghtVll9yGKJI0AaB0uI8GypfWxLTaIB0ZL8//yN3nAEIKMhf/RRilYTsn/rKj2NUa7vt2edYILi3lttOUlCBOwTc9amiRms1W8Lwr/3IdWPeBLvLuH1zNJRm2lBAwU4LBSqaOwhGaxOQr6KHTnWudhNhgOucxpZfvfI/dFw=
- secure: yERYCf7AwL11D9uMtacly/THGV8BlzsMmrt+iQVvGA3GaY6QMmfYqf6P6cCH98sH5etd1Y+1e6YrPeMjqI6lyRllT7FptoyOdHulazQe86VQN4sc0EpqMlH088kB7gGjTut9Z+X9ViooT5XEh9WA5jXEI9pXhQJNoIHkWPuwGuY=
cache:
directories:
- node_modules
- node_modules
-2
View File
@@ -141,8 +141,6 @@ module.exports = function(grunt) {
{browserName: 'firefox', version: '3.6'},
{browserName: 'safari', version: 7, platform: 'OS X 10.9'},
{browserName: 'safari', version: 6, platform: 'OS X 10.8'},
{browserName: 'opera', version: 12},
{browserName: 'opera', version: 11},
{browserName: 'internet explorer', version: 11, platform: 'Windows 8.1'},
{browserName: 'internet explorer', version: 10, platform: 'Windows 8'},
{browserName: 'internet explorer', version: 9, platform: 'Windows 7'},
+3 -3
View File
@@ -65,11 +65,11 @@ embedded in them, as well as the text for a link:
```js
Handlebars.registerHelper('link_to', function() {
return "<a href='" + this.url + "'>" + this.body + "</a>";
return new Handlebars.SafeString("<a href='" + Handlebars.Utils.escapeExpression(this.url) + "'>" + Handlebars.Utils.escapeExpression(this.body) + "</a>");
});
var context = { posts: [{url: "/hello-world", body: "Hello World!"}] };
var source = "<ul>{{#posts}}<li>{{{link_to}}}</li>{{/posts}}</ul>"
var source = "<ul>{{#posts}}<li>{{link_to}}</li>{{/posts}}</ul>"
var template = Handlebars.compile(source);
template(context);
@@ -321,7 +321,7 @@ Handlebars has been designed to work in any ECMAScript 3 environment. This inclu
- IE 6+
Older versions and other runtimes are likely to work but have not been formally
tested.
tested. The compiler requires `JSON.stringify` to be implemented natively or via a polyfill. If using the precompiler this is not necessary.
[![Selenium Test Status](https://saucelabs.com/browser-matrix/handlebars.svg)](https://saucelabs.com/u/handlebars)
+13
View File
@@ -75,10 +75,19 @@ var optimist = require('optimist')
'type': 'boolean',
'description': 'Removes the BOM (Byte Order Mark) from the beginning of the templates.',
'alias': 'bom'
},
'v': {
'type': 'boolean',
'description': 'Prints the current compiler version',
'alias': 'version'
}
})
.check(function(argv) {
if (argv.version) {
return;
}
var template = [0];
if (!argv._.length) {
throw 'Must define at least one template or directory.';
@@ -109,6 +118,10 @@ var fs = require('fs'),
var argv = optimist.argv,
template = argv._[0];
if (argv.version) {
return console.log(handlebars.VERSION);
}
// Convert the known list into a hash
var known = {};
if (argv.known && !Array.isArray(argv.known)) {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "handlebars",
"version": "v2.0.0-alpha.1",
"version": "2.0.0-alpha.4",
"main": "handlebars.js",
"dependencies": {}
}
+1 -1
View File
@@ -2,7 +2,7 @@
<package>
<metadata>
<id>handlebars.js</id>
<version>v2.0.0-alpha.1</version>
<version>2.0.0-alpha.4</version>
<authors>handlebars.js Authors</authors>
<licenseUrl>https://github.com/wycats/handlebars.js/blob/master/LICENSE</licenseUrl>
<projectUrl>https://github.com/wycats/handlebars.js/</projectUrl>
+1 -1
View File
@@ -1,7 +1,7 @@
module Utils from "./utils";
import Exception from "./exception";
export var VERSION = "v2.0.0-alpha.1";
export var VERSION = "2.0.0-alpha.4";
export var COMPILER_REVISION = 5;
export var REVISION_CHANGES = {
+1 -1
View File
@@ -86,7 +86,7 @@ var AST = {
// a mustache is definitely a helper if:
// * it is an eligible helper, and
// * it has at least one parameter or hash segment
this.isHelper = params.length || hash;
this.isHelper = !!(params.length || hash);
// a mustache is an eligible helper if:
// * its id is simple (a single part, not `this` or `..`)
+16 -12
View File
@@ -188,15 +188,15 @@ Compiler.prototype = {
},
hash: function(hash) {
var pairs = hash.pairs, pair;
var pairs = hash.pairs, i, l;
this.opcode('pushHash');
for(var i=0, l=pairs.length; i<l; i++) {
pair = pairs[i];
this.pushParam(pair[1]);
this.opcode('assignToHash', pair[0]);
for(i=0, l=pairs.length; i<l; i++) {
this.pushParam(pairs[i][1]);
}
while(i--) {
this.opcode('assignToHash', pairs[i][0]);
}
this.opcode('popHash');
},
@@ -276,7 +276,7 @@ Compiler.prototype = {
throw new Exception("You specified knownHelpersOnly, but used the unknown helper " + name, sexpr);
} else {
this.ID(id);
this.opcode('invokeHelper', params.length, name, sexpr.isRoot);
this.opcode('invokeHelper', params.length, id.original, sexpr.isRoot);
}
},
@@ -372,9 +372,7 @@ Compiler.prototype = {
},
pushParams: function(params) {
var i = params.length;
while(i--) {
for(var i=0, l=params.length; i<l; i++) {
this.pushParam(params[i]);
}
},
@@ -459,11 +457,17 @@ export function compile(input, options, env) {
}
return compiled.call(this, context, options);
};
ret.child = function(i) {
ret._setup = function(options) {
if (!compiled) {
compiled = compileInput();
}
return compiled.child(i);
return compiled._setup(options);
};
ret._child = function(i) {
if (!compiled) {
compiled = compileInput();
}
return compiled._child(i);
};
return ret;
}
+22 -18
View File
@@ -83,12 +83,13 @@ JavaScriptCompiler.prototype = {
this.compileChildren(environment, options);
var opcodes = environment.opcodes, opcode;
var opcodes = environment.opcodes,
opcode,
i,
l;
this.i = 0;
for(var l=opcodes.length; this.i<l; this.i++) {
opcode = opcodes[this.i];
for (i = 0, l = opcodes.length; i < l; i++) {
opcode = opcodes[i];
if(opcode.opcode === 'DECLARE') {
this[opcode.name] = opcode.value;
@@ -115,11 +116,12 @@ JavaScriptCompiler.prototype = {
compiler: this.compilerInfo(),
main: fn
};
this.context.programs.map(function(program, index) {
if (program) {
ret[index] = program;
var programs = this.context.programs;
for (i = 0, l = programs.length; i < l; i++) {
if (programs[i]) {
ret[i] = programs[i];
}
});
}
if (this.environment.usePartial) {
ret.usePartial = true;
@@ -606,11 +608,10 @@ JavaScriptCompiler.prototype = {
// [assignToHash]
//
// On stack, before: value, hash, ...
// On stack, after: hash, ...
// On stack, before: value, ..., hash, ...
// On stack, after: ..., hash, ...
//
// Pops a value and hash off the stack, assigns `hash[key] = value`
// and pushes the hash back onto the stack.
// Pops a value off the stack and assigns it to the current hash
assignToHash: function(key) {
var value = this.popStack(),
context,
@@ -914,16 +915,19 @@ JavaScriptCompiler.prototype = {
options.inverse = inverse;
}
for (var i = 0; i < paramSize; i++) {
// The parameters go on to the stack in order (making sure that they are evaluated in order)
// so we need to pop them off the stack in reverse order
var i = paramSize;
while (i--) {
param = this.popStack();
params.push(param);
params[i] = param;
if (this.trackIds) {
ids.push(this.popStack());
ids[i] = this.popStack();
}
if (this.stringParams) {
types.push(this.popStack());
contexts.push(this.popStack());
types[i] = this.popStack();
contexts[i] = this.popStack();
}
}
+27 -23
View File
@@ -70,13 +70,6 @@ export function template(templateSpec, env) {
},
programWithDepth: env.VM.programWithDepth,
initData: function(context, data) {
if (!data || !('root' in data)) {
data = data ? createFrame(data) : {};
data.root = context;
}
return data;
},
data: function(data, depth) {
while (data && depth--) {
data = data._parent;
@@ -99,28 +92,31 @@ export function template(templateSpec, env) {
var ret = function(context, options) {
options = options || {};
var namespace = options.partial ? options : env,
helpers,
var helpers,
partials,
data = options.data;
if (!options.partial) {
helpers = container.helpers = container.merge(options.helpers, namespace.helpers);
if (templateSpec.usePartial) {
partials = container.partials = container.merge(options.partials, namespace.partials);
}
if (templateSpec.useData) {
data = container.initData(context, data);
}
} else {
helpers = container.helpers = options.helpers;
partials = container.partials = options.partials;
ret._setup(options);
if (!options.partial && templateSpec.useData) {
data = initData(context, data);
}
return templateSpec.main.call(container, context, helpers, partials, data);
return templateSpec.main.call(container, context, container.helpers, container.partials, data);
};
ret.child = function(i) {
ret._setup = function(options) {
if (!options.partial) {
container.helpers = container.merge(options.helpers, env.helpers);
if (templateSpec.usePartial) {
container.partials = container.merge(options.partials, env.partials);
}
} else {
container.helpers = options.helpers;
container.partials = options.partials;
}
};
ret._child = function(i) {
return container.programWithDepth(i);
};
return ret;
@@ -164,3 +160,11 @@ export function invokePartial(partial, name, context, helpers, partials, data) {
}
export function noop() { return ""; }
function initData(context, data) {
if (!data || !('root' in data)) {
data = data ? createFrame(data) : {};
data.root = context;
}
return data;
}
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "handlebars",
"barename": "handlebars",
"version": "v2.0.0-alpha.1",
"version": "2.0.0-alpha.4",
"description": "Handlebars provides the power necessary to let you build semantic templates effectively with no frustration",
"homepage": "http://www.handlebarsjs.com/",
"keywords": [
@@ -42,7 +42,7 @@
"grunt-contrib-requirejs": "~0.4.1",
"grunt-contrib-uglify": "~0.2.2",
"grunt-contrib-watch": "~0.5.3",
"grunt-saucelabs": "~4.1.2",
"grunt-saucelabs": "~5.0.1",
"es6-module-packager": "1.x",
"jison": "~0.3.0",
"keen.io": "0.0.3",
+27 -1
View File
@@ -2,7 +2,33 @@
## Development
[Commits](https://github.com/wycats/handlebars.js/compare/v2.0.0-alpha.1...master)
[Commits](https://github.com/wycats/handlebars.js/compare/v2.0.0-alpha.4...master)
## v2.0.0-alpha.4 - May 19th, 2014
- Expose setup wrappers for compiled templates - 3638874
[Commits](https://github.com/wycats/handlebars.js/compare/v2.0.0-alpha.3...v2.0.0-alpha.4)
## v2.0.0-alpha.3 - May 19th, 2014
- [#797](https://github.com/wycats/handlebars.js/pull/797) - Pass full helper ID to helperMissing when options are provided ([@tomdale](https://api.github.com/users/tomdale))
- [#793](https://github.com/wycats/handlebars.js/pull/793) - Ensure isHelper is coerced to a boolean ([@mmun](https://api.github.com/users/mmun))
- Refactor template init logic - 085e5e1
[Commits](https://github.com/wycats/handlebars.js/compare/v2.0.0-alpha.2...v2.0.0-alpha.3)
## v2.0.0-alpha.2 - March 6th, 2014
- [#756](https://github.com/wycats/handlebars.js/pull/756) - fix bug in IE<=8 (no Array::map), closes #751 ([@jenseng](https://api.github.com/users/jenseng))
- [#749](https://github.com/wycats/handlebars.js/pull/749) - properly handle multiple subexpressions in the same hash, fixes #748 ([@jenseng](https://api.github.com/users/jenseng))
- [#743](https://github.com/wycats/handlebars.js/issues/743) - subexpression confusion/problem? ([@waynedpj](https://api.github.com/users/waynedpj))
- [#746](https://github.com/wycats/handlebars.js/issues/746) - [CLI] support `handlebars --version` ([@apfelbox](https://api.github.com/users/apfelbox))
- [#747](https://github.com/wycats/handlebars.js/pull/747) - updated grunt-saucelabs, failing tests revealed ([@Jonahss](https://api.github.com/users/Jonahss))
- Make JSON a requirement for the compiler. - 058c0fb
- Temporarily kill the AWS publish CI step - 8347ee2
Compatibility notes:
- A JSON polyfill is required to run the compiler under IE8 and below. It's recommended that the precompiler be used in lieu of running the compiler on these legacy environments.
[Commits](https://github.com/wycats/handlebars.js/compare/v2.0.0-alpha.1...v2.0.0-alpha.2)
## v2.0.0-alpha.1 - February 10th, 2014
- [#182](https://github.com/wycats/handlebars.js/pull/182) - Allow passing hash parameters to partials ([@kpdecker](https://api.github.com/users/kpdecker))
+32 -1
View File
@@ -23,6 +23,7 @@
mocha.setup('bdd');
</script>
<script src="/spec/env/json2.js"></script>
<script src="/spec/env/require.js"></script>
<script src="/spec/env/common.js"></script>
@@ -62,11 +63,41 @@
window.Handlebars = Handlebars['default'];
require(['tests'], function(Handlebars) {
mocha.globals(['mochaResults'])
// The test harness leaks under FF. We should have decent global leak coverage from other tests
if (!navigator.userAgent.match(/Firefox\/([\d.]+)/)) {
mocha.checkLeaks();
}
mocha.run();
var runner = mocha.run();
//Reporting for saucelabs
var failedTests = [];
runner.on('end', function(){
window.mochaResults = runner.stats;
window.mochaResults.reports = failedTests;
});
runner.on('fail', logFailure);
function logFailure(test, err){
var flattenTitles = function(test){
var titles = [];
while (test.parent.title){
titles.push(test.parent.title);
test = test.parent;
}
return titles.reverse();
};
failedTests.push({
name: test.title,
result: false,
message: err.message,
stack: err.stack,
titles: flattenTitles(test)
});
};
});
});
};
+489
View File
@@ -0,0 +1,489 @@
/*
json2.js
2014-02-04
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx,
escapable,
gap,
indent,
meta,
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
+8
View File
@@ -291,6 +291,7 @@ describe('helpers', function() {
shouldCompileTo(string, [hash, helpers], "Message: Goodbye cruel world", "block helpers with multiple params");
});
});
describe('hash', function() {
it("helpers can take an optional hash", function() {
var template = CompilerContext.compile('{{goodbye cruel="CRUEL" world="WORLD" times=12}}');
@@ -473,6 +474,9 @@ describe('helpers', function() {
blockHelperMissing: function() {
return 'missing: ' + arguments[arguments.length-1].name;
},
helperMissing: function() {
return 'helper missing: ' + arguments[arguments.length-1].name;
},
helper: function() {
return 'ran: ' + arguments[arguments.length-1].name;
}
@@ -502,6 +506,10 @@ describe('helpers', function() {
it('should include full id', function() {
shouldCompileTo('{{#foo.helper}}{{/foo.helper}}', [{foo: {}}, helpers], 'missing: foo.helper');
});
it('should include full id if a hash is passed', function() {
shouldCompileTo('{{#foo.helper bar=baz}}{{/foo.helper}}', [{foo: {}}, helpers], 'helper missing: foo.helper');
});
});
describe('name conflicts', function() {
+32 -1
View File
@@ -24,6 +24,7 @@
</script>
<script src="/dist/handlebars.js"></script>
<script src="/spec/env/json2.js"></script>
<script src="/spec/env/common.js"></script>
<script>
var CompilerContext = {
@@ -50,11 +51,41 @@
<script src="/tmp/tests.js"></script>
<script>
onload = function(){
mocha.globals(['mochaResults'])
// The test harness leaks under FF. We should have decent global leak coverage from other tests
if (!navigator.userAgent.match(/Firefox\/([\d.]+)/)) {
mocha.checkLeaks();
}
mocha.run();
var runner = mocha.run();
//Reporting for saucelabs
var failedTests = [];
runner.on('end', function(){
window.mochaResults = runner.stats;
window.mochaResults.reports = failedTests;
});
runner.on('fail', logFailure);
function logFailure(test, err){
var flattenTitles = function(test){
var titles = [];
while (test.parent.title){
titles.push(test.parent.title);
test = test.parent;
}
return titles.reverse();
};
failedTests.push({
name: test.title,
result: false,
message: err.message,
stack: err.stack,
titles: flattenTitles(test)
});
};
};
</script>
</head>
+1 -1
View File
@@ -147,7 +147,7 @@ describe('string params mode', function() {
var template = CompilerContext.compile('{{#with content}}{{#view}}{{firstName}} {{lastName}}{{/view}}{{/with}}', {stringParams: true});
var helpers = {
with: function(options) {
'with': function(options) {
return "WITH";
},
view: function() {
+32
View File
@@ -29,6 +29,21 @@ describe('subexpressions', function() {
shouldCompileTo(string, [context, helpers], "val is true");
});
it("mixed paths and helpers", function() {
var string = '{{blog baz.bat (equal a b) baz.bar}}';
var context = { bar: "LOL", baz: {bat: 'foo!', bar: 'bar!'} };
var helpers = {
blog: function(val, that, theOther) {
return "val is " + val + ', ' + that + ' and ' + theOther;
},
equal: function(x, y) {
return x === y;
}
};
shouldCompileTo(string, [context, helpers], "val is foo!, true and bar!");
});
it("supports much nesting", function() {
var string = '{{blog (equal (equal true true) true)}}';
@@ -89,6 +104,23 @@ describe('subexpressions', function() {
shouldCompileTo(string, [{}, helpers], "val is true");
});
it("multiple subexpressions in a hash", function() {
var string = '{{input aria-label=(t "Name") placeholder=(t "Example User")}}';
var helpers = {
input: function(options) {
var hash = options.hash;
var ariaLabel = Handlebars.Utils.escapeExpression(hash['aria-label']);
var placeholder = Handlebars.Utils.escapeExpression(hash.placeholder);
return new Handlebars.SafeString('<input aria-label="' + ariaLabel + '" placeholder="' + placeholder + '" />');
},
t: function(defaultString) {
return new Handlebars.SafeString(defaultString);
}
}
shouldCompileTo(string, [{}, helpers], '<input aria-label="Name" placeholder="Example User" />');
});
it("in string params mode,", function() {
var template = CompilerContext.compile('{{snog (blorg foo x=y) yeah a=b}}', {stringParams: true});