Compare commits

...

445 Commits

Author SHA1 Message Date
kpdecker afe730e059 v3.0.1 2015-03-24 14:22:38 -05:00
kpdecker 40894e619b Update release notes 2015-03-24 14:22:22 -05:00
Kevin Decker 1d401a2abc Merge pull request #984 from johneke/master
Adding documentation for passing arguments into partials
2015-03-24 14:20:22 -05:00
johneke a10d907a65 Update README.markdown 2015-03-18 22:55:26 -04:00
johneke fed86c01ad Adding documentation for parameters in partials 2015-03-18 20:23:15 -04:00
kpdecker ab96073c6b Optimize hot path in escapeExpression
Avoid deoptimizations in v8 due to the duct type check on string instances.

Partial fix for #973
2015-03-16 22:06:01 -05:00
kpdecker 64ab232d72 Fix --version flag
Fixes #966
2015-02-28 19:58:23 -06:00
Kevin Decker 8c357b9243 Merge pull request #964 from grassick/patch-1
default is a reserved word
2015-02-28 16:26:39 -06:00
grassick 71690ae39d default is a reserved word
Quoting it to fix in older browsers, especially Android 2.3.x.
2015-02-18 10:57:02 -05:00
Kevin Decker 3c9ff77e68 Merge pull request #962 from pismute/master
Add dashbars' link on README.
2015-02-16 09:01:07 -06:00
Changwoo Park 5ede36b8fd Add dashbars' link on README. 2015-02-16 19:29:13 +09:00
kpdecker c15f90e513 Fix typo 2015-02-10 20:40:53 -06:00
kpdecker 0099e16a01 v3.0.0 2015-02-10 00:14:55 -06:00
kpdecker a8848d0af9 Update release notes 2015-02-10 00:14:42 -06:00
kpdecker ca6152d2f7 Merge branch 'marcioj-boolean-literals' 2015-02-09 23:55:25 -06:00
kpdecker 55dc82d938 Update AST docs for literal helper names 2015-02-09 23:55:01 -06:00
kpdecker 39121cf8f5 Handle all potential literal values
Adds support for literal helper names in a few missing cases such as block expressions and subexpressions.
2015-02-09 23:54:46 -06:00
Marcio Junior 07f27843dc Transform literals to path expressions in mustache nodes 2015-02-08 19:31:38 -02:00
Marcio Junior 5cc326d425 Test compilation of literal values in mustaches 2015-02-08 19:31:38 -02:00
Marcio Junior f857471cc8 Boolean literals can be passed to mustaches 2015-02-08 19:31:38 -02:00
kpdecker fd8484798c Fix console.log cleanup 2015-02-07 14:31:54 -06:00
kpdecker 810d86d474 Fix global leak in test 2015-02-07 13:28:27 -06:00
kpdecker cfbef2585d Fail over to console.log if lacking console method
This improves logger resiliency under older browsers.
2015-02-07 13:23:10 -06:00
kpdecker 95421271e3 Change default log level to info
Eventually we want to fix this API so that you can provide per-instance levels, etc but for now this is a quick fix.

Fixes wycats/handlebars-site#91
2015-02-07 12:31:19 -06:00
Kevin Decker 752a28f24c Merge pull request #943 from ogennadi/patch-2
Properly formatted dot
2015-01-21 06:16:21 -06:00
Kevin Decker 05bda7ed0c Merge pull request #944 from ogennadi/patch-3
Clarified a long sentence
2015-01-21 06:15:58 -06:00
Oge Nnadi 1f6a94424d Clarified a long sentence 2015-01-20 11:01:11 -08:00
Oge Nnadi 8626fa8bbe Properly formatted dot 2015-01-20 10:59:38 -08:00
Kevin Decker 9f8daf9076 Merge pull request #941 from wycats/dynamic-partial
Add support for dynamic partial names
2015-01-18 20:13:25 -06:00
kpdecker 884bf15536 Avoid direct references to sexpr in statements
This allows us to avoid creating unnecessary AST nodes and avoids things like isHelper.

Side effect of these changes is that @data functions can now have data parameters passed to them.
2015-01-18 17:27:27 -06:00
kpdecker 999da739a6 Update for proposed SubExpression dependency break
Avoids parsing against SubExpressions and instead inlines the content that a subexpression otherwise would have. This can still be based via duck typing so should not add much overhead to the compiler.
2015-01-18 14:21:04 -06:00
kpdecker d567d9c345 Update PartialExpression AST docs 2015-01-18 13:29:15 -06:00
kpdecker cb51b82b8e Add support for dynamic partial names
Uses the subexpression syntax to allow for dynamic partial lookups. Ex:

```
{{> (helper) }}
```

Fixes #933
2015-01-18 13:23:45 -06:00
kpdecker b0b522b4f8 Add tests for partial comment whitespace control 2015-01-17 19:19:30 -06:00
kpdecker 3cf47abe19 Include error info when throwing type error 2015-01-17 19:19:30 -06:00
Kevin Decker b7488acf89 Merge pull request #940 from mattflaschen/addMissingReservedWords
Add missing reserved words so compiler knows to use array syntax:
2015-01-17 18:32:58 -06:00
Matthew Flaschen c9d723e0fb Add missing reserved words so compiler knows to use array syntax:
* await
* null
* true
* false

IE 8 was failing to compile Handlebars-generated source code
because it had helpers.null.

I came up with this list by diffing
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords
against the ones Handlebars already had.

I added two corresponding tests for nameLookup.
2015-01-17 19:04:38 -05:00
kpdecker c5fe2527b3 Ignore coverage dir in npm package
Fixes #937
2015-01-17 14:51:49 -06:00
Kevin Decker 9c40c07941 Merge pull request #938 from diwo/patch-1
Fix example using #with helper
2015-01-15 10:57:23 -08:00
Dickson Wong 9c7641f63f Fix example using #with helper
Example using #with helper should close tag using {{/with}}
2015-01-14 15:46:54 -08:00
Kevin Decker 96a5cf5ba1 Merge pull request #932 from wycats/strict
Implement strict and assumeObject modes
2014-12-31 19:28:05 -06:00
Kevin Decker 4b2146b12d Merge pull request #930 from wycats/visitor-update
Add parent tracking and mutation to AST visitors
2014-12-29 16:59:21 -06:00
kpdecker 6650957f79 Implement strict and assumeObject modes
Causes templates to throw when lookup fields are not defined within the context. Strict mode will throw when any field is omitted. assumeObjects mode maintains the existing behavior of outputting an empty response when fields are not defined but allows for performance/size optimizations by not doing safety checks for intermediate objects in the lookup chain.

Strict mode effectively disables the helperMissing and inverse handling for blockHelperMissing as templates will throw rather than call those features for missing data fields.

Fixes #651
Fixes #805
2014-12-27 14:59:36 -06:00
kpdecker ec798a7c44 Merge branch 'master' into visitor-update 2014-12-27 13:30:20 -06:00
kpdecker b764fb1ded Fix sourcemap test 2014-12-27 13:17:55 -06:00
kpdecker 0a9fc171b0 Fix block param evaluation under older IE 2014-12-27 13:13:52 -06:00
kpdecker 9c9a972a0c Safely handle source map in browser tests 2014-12-27 13:01:13 -06:00
kpdecker b474630c7d Strip unnecessary whitespace in template output 2014-12-27 12:58:28 -06:00
kpdecker f147050513 Update dependencies 2014-12-27 12:12:21 -06:00
kpdecker daa8f3dd05 Fix duplicate return statement on simple templates 2014-12-27 10:05:05 -06:00
kpdecker be0ba75925 Fix case-insensitive file system compile issue 2014-12-26 11:34:48 -06:00
kpdecker 9ff3daf785 Add parent tracking and mutation to AST visitors
Fixes #916
2014-12-26 11:32:30 -06:00
kpdecker 8babe05953 Bump code coverage 2014-12-26 11:12:47 -06:00
kpdecker 396795c983 Implement block parameters
Fixes #907
2014-12-26 00:31:57 -06:00
kpdecker 9e907e6785 Expose AST helpers in public API 2014-12-21 22:32:50 -06:00
kpdecker 6d2239d8ac Update fix for #926 for 3.0 codeline 2014-12-17 00:40:28 -06:00
kpdecker 59e80c5103 Track depths on deduped children
Fixes a very specific error case where deduped children won’t receive the depths object due to it being omitted by the caller when optimizing.

Fixes #926
2014-12-16 17:59:32 -06:00
kpdecker 69b1bdd32e Avoid unnecessary this. reference 2014-12-16 12:57:46 -06:00
kpdecker c05fad8b18 Fix remaining depth arg 2014-12-16 12:57:46 -06:00
kpdecker 203df9d5b7 Remove unused vars and add jshint checking 2014-12-16 12:57:46 -06:00
kpdecker 0d396ccd30 Remove Compiler.depths parameter
This is no longer necessary with the depths array tracking and adds compiler overhead.
2014-12-16 12:57:46 -06:00
Kevin Decker ae8c1d229f Merge pull request #918 from oneeman/submodule-instr-in-contributing
Add instructions for 'spec/mustache' to CONTRIBUTING.md, fix a few typos
2014-12-08 11:39:22 -08:00
Or Neeman e7f51c2248 Add instructions for 'spec/mustache' to CONTRIBUTING.md, fix a few typos elsewere 2014-12-07 09:00:56 -06:00
kpdecker 3238645f26 Allow blockParams on chained inverse statements 2014-11-29 18:38:22 -06:00
kpdecker f84f76f006 Add basic docs for JavaScriptCompiler override API 2014-11-29 18:20:11 -06:00
kpdecker 96c1300f15 Drop unused JavaScriptCompiler.namespace param 2014-11-29 18:11:58 -06:00
kpdecker b6ba2dcdb0 Move compileProgram out of visitor methods 2014-11-29 18:02:58 -06:00
kpdecker 5b0efc7e91 Track source node via accept call rather vs opcode 2014-11-29 18:02:58 -06:00
Kevin Decker d4070c3667 Merge pull request #915 from wycats/ast-update
Ast update
2014-11-29 18:02:12 -06:00
kpdecker a655aedb5c s/Subexpression/SubExpression/ 2014-11-29 17:59:09 -06:00
kpdecker 928ba56b95 Rework strip flags to make clearer at in AST level
Rather than keeping state in the AST, which requires some gymnastics, we create a separate visitor flow which does the top down iteration necessary to calculate all of the state needed for proper whitespace control evaluation.
2014-11-28 23:13:06 -06:00
kpdecker 8a6796e5c0 Move Jison parsing out of AST into helpers 2014-11-28 17:26:52 -06:00
kpdecker 95b23095c0 First crack at compiler API docs 2014-11-28 16:55:53 -06:00
kpdecker ffc9fb5007 Add original to BooleanLiteral 2014-11-28 16:55:41 -06:00
kpdecker 6a7a8c803d Rename AST objects to match type names 2014-11-28 14:42:24 -06:00
kpdecker f990cf0064 Treat partial exec in a manner closer to helpers
This helps unify the code handling and will also be needed to support string/id tracking on partials.
2014-11-27 09:11:03 -06:00
kpdecker 1124908d2a Update subexpression and hash AST constructs 2014-11-27 08:37:48 -06:00
kpdecker e1cba432a6 Simplify Path and Sexpr calculated flags 2014-11-27 07:32:15 -06:00
kpdecker 5c921cafeb Replace DataNode and IdNode with PathNode
This is a breaking change for string mode users as there is no longer a distinct type for data parameters. Instead data consumers should look for the @ prefix value.
2014-11-26 20:36:36 -06:00
kpdecker 697bbe59ca Update literal ast nodes for new spec 2014-11-26 19:22:09 -06:00
kpdecker 2a4819d75c Update statement node ASTs 2014-11-26 19:04:18 -06:00
kpdecker 5cfe6a0be1 Update MustacheNode for new AST structure 2014-11-26 09:31:46 -06:00
kpdecker df421f1e4b Update ProgramNode to better match SpiderMonkey 2014-11-26 09:18:33 -06:00
kpdecker 61dd721ca2 Update AST location info to match SpiderMonkey
Part of #889
2014-11-26 09:01:03 -06:00
kpdecker 3a9440f954 Make each helper data uniform
Provide @key and @last value for all forms of iteration.

Fixes #910
2014-11-26 08:02:55 -06:00
kpdecker e4c874d1af Update to latest es6-module-packager 2014-11-26 08:00:23 -06:00
kpdecker 5594416121 Export the default object for handlebars/runtime
Maintains consistency with the prior export pattern, while avoids the knarly default loading issues.
2014-11-26 07:49:29 -06:00
kpdecker c4b3c901a5 Provide Handlebars.noConflict implementation
Allows for users who are loading via a global pattern to avoid conflicting with other instances of the library.

Fixes #887
2014-11-26 07:48:45 -06:00
kpdecker 617dd57162 Lookup partials when undefined 2014-11-25 23:15:11 -06:00
kpdecker d044a8c99d Optimize variable declaration 2014-11-25 23:15:11 -06:00
Kevin Decker bf993528d1 Merge pull request #906 from mmun/block-params
Add parser support for block params
2014-11-12 21:36:25 -06:00
Martin Muñoz b8a9f7264d Add parser support for block params 2014-11-11 21:35:10 -05:00
Kevin Decker b3b5b35889 Merge pull request #856 from MajorBreakfast/patch-1
jspm compatibility
2014-11-11 15:05:10 -06:00
MajorBreakfast 80b5b24cce jspm compatibility
This will enable compatibilty with jspm as soon as https://github.com/wycats/handlebars.js/issues/855 has been addressed.
2014-11-10 15:12:58 +01:00
kpdecker 4a2afa9d02 Propagate options for client compiled partials
Fixes #901
2014-11-08 19:06:40 -06:00
kpdecker 4415f3151d Merge branch 'mmun-remove-block-mustache' 2014-11-08 18:57:19 -06:00
kpdecker bf8cc50798 Merge branch 'remove-block-mustache' of github.com:mmun/handlebars.js into mmun-remove-block-mustache
Conflicts:
	lib/handlebars/compiler/helpers.js
	spec/parser.js
2014-11-08 18:57:06 -06:00
kpdecker ac208b1bcd Only provide aliases for multiple use calls
Fixes #903
2014-11-08 18:53:43 -06:00
kpdecker 8dfeabdd16 Fix missing coverage 2014-11-08 18:11:29 -06:00
kpdecker 6d7696ef66 Remove unnecessary test stub 2014-11-08 18:09:15 -06:00
Kevin Decker 8e6e9fbc60 Merge pull request #902 from wycats/source-map
Generate Source Maps
2014-11-08 18:04:56 -06:00
kpdecker 1429587dd4 Provide default mapping for boilerplate code 2014-11-08 17:50:01 -06:00
kpdecker 0dbeeb4503 Add source map output support to the CLI 2014-11-08 17:50:01 -06:00
kpdecker 3ee0682247 Generate source maps
Allow the precompiler to generate source maps when the srcFile parameter is passed.

This refactors large chunks of the code generation pipeline, allowing metadata to be associated with code chunks as well as breaking out much of the code generation logic into a separate helper.
2014-11-08 17:50:01 -06:00
kpdecker 249f559104 Include location information in all opcodes 2014-11-08 17:50:01 -06:00
Kevin Decker ea6b0be910 Merge pull request #892 from wycats/else-if
Implement parser for else chaining of helpers
2014-11-08 17:49:14 -06:00
Kevin Decker e779ecf12d Merge pull request #890 from wycats/to-html-safe
Use toHTML vs. instanceof checks for SafeString
2014-11-08 17:47:25 -06:00
kpdecker 01a22e61df Use toHTML vs. instanceof checks for SafeString
Allows for us to play nicely in environments such as Node that could have multiple versions of the library loaded. Also allows for implementors to provide their own behavior, provided they know what they are doing.

Fixes #886
2014-11-08 17:46:53 -06:00
Kevin Decker c8af90f697 Merge pull request #863 from tomByrer/patch-1
+ jsDelivr CDN info
2014-11-08 17:44:22 -06:00
Kevin Decker b5f03c95ab Merge pull request #870 from max-b/master
Registering undefined partial throws exception.
2014-11-08 17:43:41 -06:00
kpdecker d595ebc0e2 Simplify program generation logic 2014-11-08 14:36:17 -06:00
kpdecker d47e4dd1f7 Bump test coverage 2014-11-08 14:35:23 -06:00
kpdecker 83bcbee222 Ignore unused code paths
We don’t want to remove these as the generic code may need it in the future, but these code paths are not triggered through the existing language constructs.
2014-11-08 14:35:23 -06:00
kpdecker 30034c75e7 Merge setupParams and setupOptions 2014-11-06 09:43:43 -06:00
kpdecker d3bd1a523d Simplify flushInline implementation 2014-11-05 23:23:43 -06:00
kpdecker 9665379cdc Use terinary operator for inline appends
Allows for append operations to avoid breaking inline chain.
2014-11-05 22:28:12 -06:00
kpdecker a7000f8129 Provide stubbed visitor implementation
Part of #889
2014-11-05 21:57:09 -06:00
Martin Muñoz a5d0491d57 Remove RawBlockNode in favor of prepareRawBlock helper 2014-11-05 11:00:39 -05:00
Martin Muñoz 12e3d210e8 Simplify BlockNode by removing intermediate MustacheNode 2014-11-02 18:19:20 -05:00
kpdecker 632fadcea3 Add preventIndent option for partials
This disables the standalone partial indent behavior required by the Mustache spec and allows for users to utilize partials in the same manner as under 1.x.

Fixes #858
2014-11-02 12:19:56 -06:00
kpdecker 7c220b9af5 Add test for whitespace control w/ partial indent
Verifies the behaviors discussed in #858
2014-11-02 12:09:37 -06:00
kpdecker f30b3ea329 Allow whitespace control on comments
This changes the call signature for the CommentNode constructor, which is a potentially breaking change for AST users.

Fixes #866
2014-11-02 11:55:52 -06:00
kpdecker 9fbf7aa753 Fix help message for CLI
Fixes #895
2014-11-02 11:08:42 -06:00
Kevin Decker 3e1840a75d Merge pull request #874 from ogwiz2/patch-1
Capitalization change in comments for consistency
2014-10-27 23:12:25 -05:00
kpdecker 4282668d47 Implement parser for else chaining of helpers
Allows users to chain multiple helpers together using their inverse callbacks. I.e.

```
{{#if foo}}
{{else if bar}}
{{else}}
{{/if}}
```

The control flow here effectively causes the helpers to be nested. The above is actually syntactic sugar for this:

```
{{#if foo}}
{{else}}
  {{#if bar}}
  {{else}}
  {{/if}}
{{/if}}
```

Any helper may be used in this manner, the only requirement is they support normal calls and inverse calls.

Introduces a breaking change in that `{{else foo}}` may no longer be used as a root level operator. Instead `{{^foo}}` must be used.

Fixes #72.
2014-10-27 19:17:16 -05:00
Alex Jeng 4aab967796 Capitalization change in comments for consistency 2014-09-23 11:59:30 -07:00
Maxb b87e601063 Fixing indentation in spec/partials.js 2014-09-19 11:46:02 -07:00
Maxb a0e2e200d9 Registering undefined partial throws exception. 2014-09-19 11:35:16 -07:00
Kevin Decker 3133af2a21 Merge pull request #869 from jonsadka/patch-1
Update FAQ.md
2014-09-19 01:02:40 -05:00
Jon Sadka 5fe7ef63d8 Update FAQ.md
Fixed misspelling of sufficent to sufficient on Line 60
2014-09-18 22:08:51 -07:00
tomByrer 62ed555b2c + jsDelivr CDN info
Thanks to libgrabber, every time a [new release is posted](https://github.com/components/handlebars.js/releases), jsDelivr will find it & automatically upload it.  If you change your file structure, please updated the [include section](https://github.com/jsdelivr/jsdelivr/blob/master/files/handlebarsjs/update.json) or ask us to do it.

I was going to link CDNJS, but they [haven't uploaded to v2.0.0](http://cdnjs.com/libraries/handlebars.js).  Nothing against those cats; we [use their network](http://www.jsdelivr.com/network.php).
2014-09-06 08:08:23 -06:00
kpdecker 8aa2a34a8d Update jsfiddle link 2014-09-02 00:14:10 -05:00
kpdecker aaa590d846 Fix non-prerelease handling for gemspec 2014-09-01 21:42:45 -05:00
kpdecker 1eb2b04aa1 v2.0.0 2014-09-01 21:28:59 -05:00
kpdecker 2e75199664 Update release notes 2014-09-01 21:28:51 -05:00
kpdecker 0670f656fb Update jsfiddle to 2.0.0-beta.1 2014-08-27 09:27:57 -05:00
kpdecker 4d17e3c209 Add contrib note regarding handlebarsjs.com docs 2014-08-27 01:49:52 -05:00
kpdecker 58fb258016 Cleanup var names slightly 2014-08-27 01:49:23 -05:00
kpdecker ed3ae9af59 Drop cdnjs release step 2014-08-26 19:38:40 -05:00
kpdecker 64d5481c00 Play nice with gemspec version numbers 2014-08-26 19:38:32 -05:00
kpdecker cee52ea68f v2.0.0-beta.1 2014-08-26 18:32:15 -05:00
kpdecker d33b362d97 Update release notes 2014-08-26 18:27:11 -05:00
Kevin Decker c5acea75aa Update FAQ.md 2014-08-25 23:37:40 -05:00
kpdecker 4f01f650dc Render false literal as “false”
Fixes #827
2014-08-25 23:35:43 -05:00
kpdecker 3c869866c8 Update FAQ with comment on UMD vs. AMD build
Fixes #796
2014-08-25 22:55:05 -05:00
kpdecker ca1486b960 Prune unused code 2014-08-25 22:39:17 -05:00
kpdecker dfca676d63 Fix test path 2014-08-25 22:39:01 -05:00
kpdecker 09d3c74c7f Convert build to expose UMD from the default files 2014-08-25 22:06:15 -05:00
kpdecker c98147b31f Move uglify include past conditional 2014-08-25 22:05:38 -05:00
kpdecker b41459055a Expose default compatibility wrapper for umd build 2014-08-25 22:04:11 -05:00
kpdecker 84342b6215 Add template isTop flag 2014-08-25 21:15:26 -05:00
kpdecker 24d63b6966 Update Ember testing instructions 2014-08-25 21:14:56 -05:00
kpdecker 36f00db073 Fix compiler version tag 2014-08-25 21:13:31 -05:00
kpdecker 64f422b57f Rev runtime version 2014-08-25 13:49:20 -05:00
kpdecker dc9a2ed7eb Refactor content blocks to ignore lines
We can simplify our previous standalone determination logic by merging content blocks again.

Fixes #854
2014-08-25 13:27:28 -05:00
kpdecker 980c38cebf Expose escapeExpression on the root object 2014-08-25 00:34:19 -05:00
kpdecker 31f6fd7131 Merge mustache compatibility sections 2014-08-25 00:34:05 -05:00
kpdecker c9886fdc0f FAQ tweaks 2014-08-25 00:33:46 -05:00
kpdecker 501a640330 Allow passing depths to _child 2014-08-25 00:32:57 -05:00
kpdecker 477a26913a Optimize compiler opcode call 2014-08-24 18:16:11 -05:00
kpdecker 4ce474d3e4 Update issue filing guidelines 2014-08-24 15:56:27 -05:00
kpdecker 3e6bf8b0f6 Link to current performance tests in readme 2014-08-24 15:45:10 -05:00
kpdecker e5aeca648a Create CONTRIBUTING.md
Cleans up some of the process focused content in the README and also adds nice message to github issue tracker, etc.
2014-08-24 15:28:22 -05:00
kpdecker 2b3fdf7ea8 Additional test coverage cleanup
Also fixes the template._child implementation which broke with the depthed work.
2014-08-23 18:52:30 -05:00
kpdecker 0c7c37df6a Restore helperMissing for ambiguous statements
Fixes #318 (regression)
Partial fix for #783
2014-08-23 18:26:57 -05:00
kpdecker cde008b49f Cleanup from code coverage report 2014-08-23 17:44:45 -05:00
kpdecker 84d646bb5d Move strip processing into AST helper logic
We already have to track these behaviors for the standalone parsing and rather than having two whitespace pruning implementations this moves all of the behavior into one place.

Fixes #852
2014-08-23 17:44:20 -05:00
kpdecker ccd803ff15 Replace string value rather than add omit flag 2014-08-23 16:37:30 -05:00
kpdecker 0528b91644 Add original value tracking to ContentNode 2014-08-23 16:33:14 -05:00
kpdecker 35b196d069 Merge branch 'mmun-refactor-parser' 2014-08-23 16:29:50 -05:00
kpdecker 529e2b6796 Merge branch 'refactor-parser' of github.com:mmun/handlebars.js into mmun-refactor-parser
Conflicts:
	lib/handlebars/compiler/ast.js
	spec/ast.js
	src/handlebars.yy
2014-08-23 16:29:22 -05:00
kpdecker 3531e04117 Optimize replaceStack for inline methods
Only use case was with inline input so most of this code was unnecessary.
2014-08-23 07:43:09 -05:00
kpdecker c3fde1c01c Remove unnecessary stack variable from blockHelper 2014-08-23 07:42:24 -05:00
kpdecker 67b3f40eb2 Merge branch 'evensoul-master' 2014-08-23 07:36:16 -05:00
kpdecker 19ce981296 Do not flush subexpressions
They are no longer duplicated with the new helper calling pattern and this also introduced stack corruption issues due to improper value lookups.

Fixes #767
Fixes #768
2014-08-23 07:36:01 -05:00
Marko Zabcic f4b8c5260c added test multiple subexpressions in a hash with context 2014-08-23 06:56:22 -05:00
Kevin Decker cf343a1949 Merge pull request #849 from wycats/helper-undefined
Fix undefined handling for pathed lookups
2014-08-15 02:07:24 -05:00
kpdecker 3ce105ae89 Fix undefined handling for pathed lookups
Fixes #837
2014-08-15 01:45:50 -05:00
kpdecker ae44e071d8 Test case for #837 2014-08-15 01:45:50 -05:00
kpdecker 2f14fa57e5 Fix/simplify tests under sauce 2014-08-15 01:02:26 -05:00
kpdecker f2b5519e76 Strip dead code from javascript compiler 2014-08-15 00:40:07 -05:00
kpdecker cc5de5df3c Fix compat partial exec without data 2014-08-15 00:38:23 -05:00
kpdecker d05245b5f5 Make depthed lookup call non-literal
Prevents duplicate calls from being made.
2014-08-15 00:37:57 -05:00
kpdecker 084e8fe1b7 Provide better error on unexpected template
Fixes #806
2014-08-15 00:06:40 -05:00
kpdecker 9f07a34955 Additional test coverage 2014-08-15 00:05:37 -05:00
kpdecker 6f22ec1e01 Remove nested function eval in blockHelperMissing
This only worked when a function returned a function, which was then evaluated. This seems like unexpected behavior so this was dropped.
2014-08-14 23:10:17 -05:00
kpdecker c71ca34fd3 Add FAQ entry for .default export
Fixes #824
2014-08-14 22:00:59 -05:00
kpdecker 85b67d7f3d Use public url for spec submodule 2014-08-14 12:31:01 -05:00
kpdecker 9e3f824bf5 Fix compiler program de-duping 2014-08-14 12:27:39 -05:00
kpdecker b94656a31f Drop unused Compiler.disassemble method 2014-08-14 12:27:23 -05:00
kpdecker 3cea85b2b0 Drop unused DECLARE opcode 2014-08-14 12:27:02 -05:00
kpdecker 4d0e3c98eb Drop unused registerHelper inverse parameter 2014-08-14 12:25:58 -05:00
kpdecker cb22ee5681 Increase test coverage a touch 2014-08-14 12:25:35 -05:00
kpdecker 9ab31e1fc6 Add istanbul code coverage 2014-08-14 01:11:55 -05:00
kpdecker 1bd8d38c3c Update compatibility documentation
Provides an official statement regarding the issues discussed in #425
2014-08-14 00:48:19 -05:00
kpdecker 59607aa9ab Add mustache spec to tests 2014-08-14 00:48:19 -05:00
Kevin Decker 48263be204 Merge pull request #848 from wycats/recursive-partial
Implement partial recursive lookup
2014-08-14 00:48:01 -05:00
kpdecker 9f8110fe15 Implement partial recursive lookup 2014-08-14 00:29:25 -05:00
kpdecker 0edce6e1d1 Inherit compat flag for partials 2014-08-14 00:29:25 -05:00
Kevin Decker d95725d5fd Merge pull request #819 from wycats/compat-mode
Implement recursive field lookup
2014-08-13 21:14:32 -05:00
kpdecker c98613b711 Implement recursive field lookup in compat mode
Provides the mustache behavior of recursive lookup without the use of depthed paths.

Note that this does incur a fairly dramatic performance penalty for depthed queries.
2014-08-13 20:46:42 -05:00
kpdecker 625b00e1da Avoid depth construction overhead for non-depthed 2014-08-13 14:51:33 -05:00
kpdecker b695aaec7c Use depths array rather than passing array args
Approximately doubles the throughput performance of depthed templates and clears the way for doing recursive path lookups in pathed mode.
2014-08-13 14:11:53 -05:00
kpdecker f6dc5ad716 Create contextName helper for context lookup 2014-08-13 11:41:27 -05:00
Kevin Decker 867322adf2 Merge pull request #787 from wycats/standalone-mustaches
Remove whitespace surrounding standalone statements
2014-08-13 09:16:08 -05:00
Kevin Decker 3288f525f3 Merge pull request #846 from espadrine/patch-1
Readme: Use an SVG badge.
2014-08-12 20:49:08 -05:00
kpdecker f2a2914d4f Add additional tests for standalone partials 2014-08-12 15:38:50 -05:00
kpdecker e93d516672 Render indent for standalone partials 2014-08-12 14:41:58 -05:00
kpdecker 2a47d66ee9 Drop omitted content tags from generated output 2014-08-12 14:41:58 -05:00
kpdecker 50c657f138 Flag standalone nodes in the AST 2014-08-12 14:41:58 -05:00
kpdecker 6070179009 Track root status in ProgramNode constructor 2014-08-12 14:41:58 -05:00
kpdecker 4a4dcf1657 Parse context sections by line 2014-08-12 14:41:58 -05:00
kpdecker 6efcaaf8d1 Update to latest saucelabs lib 2014-08-12 14:32:19 -05:00
kpdecker f4af8e06b6 Allow compat flag in test specs 2014-08-11 20:10:12 -05:00
kpdecker 63c5eb7a82 Remove unused JSCompiler.register method 2014-08-11 20:10:12 -05:00
kpdecker 248ad1acae Fix type in README
Fixes #843
2014-08-11 20:08:29 -05:00
kpdecker 905f99b18c Minor test cleanup 2014-08-11 20:08:29 -05:00
Thaddee Tyl 11f85089cc Readme: Use an SVG badge.
Using the up-to-date badge design.
2014-08-08 17:23:38 +02:00
Kevin Decker 5f1bf78555 Merge pull request #833 from mmun/patch-1
Lock mocha dependency to ~1.20.0
2014-07-29 20:38:52 -05:00
Kevin Decker f374939cfd Merge pull request #823 from fractal-surfing/with-inverse
Support inverse sections on the with helper
2014-07-29 09:25:45 -05:00
Martin Muñoz eee2c4d4f2 Refactor blocks, programs and inverses 2014-07-29 02:45:50 -04:00
Martin Muñoz e11c1beb72 Lock mocha dependency to ~1.20.0 2014-07-29 02:22:35 -04:00
Dan Manges 2bdfd2a31d Support inverse sections on the with helper 2014-07-16 19:37:01 +00:00
kpdecker 271106d43f Do not lookup pathed helpers on the helper stack
Fixes #764
2014-07-12 12:50:54 -05:00
kpdecker 1fb7b51ee6 Fix rendering of paths that resolve to zero
Fixes #820
2014-07-12 11:43:45 -05:00
kpdecker c90cfe247c Use ID lookup for ambiguous helper evaluation
Final change for #731
2014-07-07 00:20:02 -05:00
kpdecker 107aa4a66a Add test case for GH-731 2014-07-07 00:01:17 -05:00
Kevin Decker 9a1eda2caf Merge pull request #731 from wycats/path-lookup
Strange behavior for {{#foo}} {{bar}} {{/foo}} when foo is 0
2014-07-06 23:56:33 -05:00
kpdecker b5a5c76ceb Rework lookup null protector logic
- Move the lookup null protection out of `nameLookup` and into that contexts that are aware of the needs for falsy vs. not displayed values.
- Optimize lookup for nested path operations

Fixes #731
2014-07-06 23:41:15 -05:00
kpdecker 4aad72d223 Move lambda resolution to runtime
This has a very positive impact on precompiled output size, particularly for known-helpers cases, and little or no impact on the throughput numbers.
2014-07-06 12:53:01 -05:00
kpdecker 704961b378 Add additional paths to path throughput test 2014-07-06 11:37:24 -05:00
kpdecker 054627adb0 Move precompiler test filter into describe
This allows us to play nicely with in-browser tests
2014-07-05 15:03:18 -05:00
kpdecker 058e7495f9 Add precompiler version FAQ entry.
Resolves #789
2014-07-05 14:45:13 -05:00
kpdecker 059532295d Move precompiler to safer location
Attempts to avoid some of the Node vs. ES6 confusion between the different styles within the application.

Also adds some simple tests in addition to the integration test.
2014-07-05 14:39:28 -05:00
Kevin Decker 0c084399e2 Merge pull request #795 from jwietelmann/master
Turn the precompile script into a wrapper around a module.
2014-07-05 12:30:24 -05:00
Kevin Decker efb17b80a6 Update FAQ styling 2014-07-05 12:22:28 -05:00
kpdecker 7890c7dc89 Add basic FAQ 2014-07-05 12:21:39 -05:00
kpdecker b79e31e5a5 Remove disassemble log statement
Fixes #772
2014-06-28 18:44:11 -07:00
kpdecker 7172d167dd Provide clear throw on {{#each}}
Fixes #773
2014-05-27 10:54:28 -04:00
kpdecker 3cdf14d294 Add test case for Issue #800
This isn’t failing in master but this is a useful test to prevent regressions.
2014-05-27 09:32:29 -04:00
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
Joel Wietelmann a14c689fa6 Stupid line ending 2014-05-10 14:11:07 -05:00
Joel Wietelmann e143849f8a Knocking the indent back to what it was to make for a less scary-looking pull request 2014-05-10 14:10:05 -05:00
Joel Wietelmann 2e7a3bd702 Turning CLI precompiler into a wrapper around a module. 2014-05-10 14:07:15 -05: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
kpdecker a5ff1f3d22 vv2.0.0-alpha.1 2014-02-10 02:11:07 -06:00
kpdecker b22a150a37 Update release notes 2014-02-10 02:01:20 -06:00
kpdecker 6da3c31494 Update compiler revision info 2014-02-10 01:50:32 -06:00
kpdecker c72a8d5e84 Add child accessor API 2014-02-09 22:48:38 -06:00
kpdecker d00d8b6776 Better docs on how to file issues 2014-02-09 22:47:40 -06:00
Kevin Decker db651e7ff4 Merge pull request #491 from wycats/data-depth
For nested helpers: get the @ variables of the outer helper from the inner one
2014-02-09 19:16:47 -06:00
kpdecker 16f135835e Add support for depthed resolution of data fields 2014-02-09 18:35:22 -06:00
Kevin Decker fcec69ae2c Merge pull request #569 from wycats/lookup-helper
Unable to lookup array values using @index
2014-02-09 17:50:28 -06:00
kpdecker 306feb497c Implement lookup helper 2014-02-09 17:22:18 -06:00
kpdecker a9f76e1475 jshint changes 2014-02-09 17:21:49 -06:00
Kevin Decker fe3b4cc98e Merge pull request #730 from wycats/jezell-master
Raw block helpers
2014-02-09 15:27:59 -06:00
kpdecker 14b7ef9066 Make raw blocks operate like blocks 2014-02-09 15:11:12 -06:00
Jesse Ezell 9b14dc40a5 raw block helpers 2014-02-09 14:41:32 -06:00
Jesse Ezell 954253305a Add {{{{ }}}} for raw blocks 2014-02-09 14:41:32 -06:00
kpdecker 7a7ad74ff1 Optimize buffer generate first and all edge cases 2014-02-09 14:24:18 -06:00
kpdecker d6e86af41a Update to latest packager version
Fixes #705
2014-02-09 13:09:38 -06:00
kpdecker 71ed8b5e93 Merge branch 'master' of github.com:wycats/handlebars.js 2014-02-09 12:20:25 -06:00
kpdecker 7a6f706dc4 Add initial copyright year 2014-02-09 12:19:55 -06:00
PatrickJS dd365eaede update copyright year 2014-02-09 12:19:27 -06:00
Kevin Decker bc8f6792e8 Merge pull request #729 from wycats/precompile-literal
Convert template spec to object literal
2014-02-08 20:01:52 -06:00
kpdecker 2812fe2775 Convert template spec to object literal
This allows for metadata to be associated with the template and a simplification of the template init logic.
2014-02-06 23:05:45 -08:00
kpdecker b0e7298523 Remove unnecessary conditional 2014-02-06 23:01:43 -08:00
kpdecker 6ca06d4115 Add depth benchmark cases 2014-02-06 22:50:12 -08:00
kpdecker 8f07bbabea Add quotes to exception 2014-01-20 00:55:53 -06:00
kpdecker 4679b1d931 Include content on binary output test failure 2014-01-18 09:29:47 -06:00
kpdecker cea57c05e2 Optimize initData for root defined case 2014-01-18 09:23:11 -06:00
kpdecker 311be67bde Add partial and helper unregister APIs
Fixes #669
2014-01-18 09:22:29 -06:00
Kevin Decker 88c52ded2e Merge pull request #712 from wycats/track-ids
Add trackIds compiler flag
2014-01-17 21:36:01 -08:00
kpdecker 5a0bcb932d Fix handler execution in nondata/nonid mode 2014-01-17 23:24:35 -06:00
kpdecker 49fcf10de2 Add contextPath tracking in builtin helpers 2014-01-17 23:15:18 -06:00
kpdecker ace2896ec8 Add trackIds compiler flag
Allows helpers that care about where a particular field came from derive this data while maintaining backward compatibility with existing helpers.
2014-01-17 23:15:17 -06:00
kpdecker 9df919083d Create track ids test stub 2014-01-17 23:15:17 -06:00
kpdecker 103e5f8409 Only lint 1 set of release content 2014-01-17 23:11:35 -06:00
kpdecker a14daca1c6 Simplify sauce test environments 2014-01-17 23:11:13 -06:00
kpdecker 33921beaa0 Fix missing parameters for pathed mustaches
Fixes #658
2014-01-17 23:09:59 -06:00
kpdecker d4cfe90959 Allow decimal number values
Fixes #472
2014-01-17 20:42:02 -06:00
kpdecker 051618c024 Always process explicitly passed files in CLI
Fixes #689
2014-01-17 20:16:10 -06:00
kpdecker fe4880feaa Allow implicit context iteration with each
Fixes #671
2014-01-17 20:13:00 -06:00
Kevin Decker 363cb4b0fb Merge pull request #182 from wycats/partial-hash
Context different for partial
2014-01-17 16:07:02 -08:00
kpdecker e290ec24f1 Test more concrete behavior in partial hash test 2014-01-17 17:51:52 -06:00
kpdecker 45ae86a248 Implement partial hash evaluation 2014-01-17 17:51:52 -06:00
kpdecker f90981adf6 Add partial hash parser support 2014-01-17 17:51:52 -06:00
Kevin Decker 93a3725480 Merge pull request #711 from wycats/git-tag
Attempt to resolve git tag using describe
2014-01-17 15:51:30 -08:00
kpdecker 1b8c0e3c76 Use git describe to lookup tag 2014-01-17 17:43:48 -06:00
kpdecker 1b0b44a5b7 Remove apt git install 2014-01-17 17:18:11 -06:00
Kevin Decker f9e0272513 Merge pull request #704 from blakeembrey/clean-compiler
JavaScript Compiler Cleanup
2014-01-17 12:49:52 -08:00
Blake Embrey 13633e7896 Improve usefulness of extend util, properly use namespace property, update setup options to use a hash helper. 2014-01-16 21:24:26 +10:00
Kevin Decker 5659db4877 Merge pull request #634 from wycats/name-option
It would be great to have the helper name passed to `blockHelperMissing`
2014-01-15 08:42:32 -08:00
Kevin Decker cb80f46843 Merge pull request #392 from wycats/root-data
Access to root context in partials and helpers
2014-01-15 08:42:11 -08:00
kpdecker f650b0d69e Expose the initial context via @root 2014-01-15 09:41:53 -06:00
Kevin Decker d841ad5962 Merge pull request #707 from wycats/git-fix
Attempt manual install of git in travis
2014-01-15 07:13:51 -08:00
kpdecker fe9e93fc4d Attempt manual install of git in travis 2014-01-15 08:57:21 -06:00
Yehuda Katz 1a91fbda40 Merge pull request #706 from scottgonzalez/readme-with
README: Use with helper instead of relying on blockHelperMissing
2014-01-14 12:39:20 -08:00
Scott González 91aa96da7d README: Use with helper instead of relying on blockHelperMissing 2014-01-14 15:35:27 -05:00
Kevin Decker db7c9f3565 Merge pull request #703 from nbibler/patch-1
Add MIT license identification to the Ruby gemspec
2014-01-09 23:04:00 -08:00
Nathaniel Bibler 76b47e3393 Add MIT license identification to the Ruby gemspec 2014-01-08 22:05:16 -05:00
kpdecker d385e2cab6 Cleanup now unused code in jscompiler 2014-01-06 16:07:56 -06:00
kpdecker 0f328f375e Include name option for all helper calls
All helper calls will have access to `options.name` which is the first id value of the mustache operation.

As part of this the helperMissing call has been simplified to remove the indexed name in order to optimize the call. This is a breaking change.

Fixes #634
2014-01-06 16:07:56 -06:00
kpdecker c73aceb3d3 Refactor out pushParams method
Simplifies hash and param push logic
2014-01-06 14:41:23 -06:00
kpdecker daeecf825c Track stringParams mode in local state vars 2014-01-06 02:55:13 -06:00
kpdecker 607748af3b Add better logging of test compile errors 2014-01-06 02:45:10 -06:00
kpdecker 7197289364 Update release instructions 2014-01-06 02:45:09 -06:00
kpdecker fc60f16475 Fix DATA value in stringParams mode
Fixes #699
2014-01-06 02:45:09 -06:00
Kevin Decker 08fab253ef Merge pull request #700 from blakeembrey/valid-js-variable
Remove redundant conditions
2014-01-05 21:15:54 -08:00
Blake Embrey 3d9685c6a2 Remove redundant conditions. 2014-01-05 12:14:24 -05:00
kpdecker 6d996ef270 Simplify ambiguous code
Remove if conditional in favor of boolean failover.
2014-01-04 09:19:58 -06:00
Kevin Decker 55c7cbbbfa Merge pull request #697 from jwilm/handlebars-in-wild-addition
Add koa-hbs to "handlebars in the wild" list
2014-01-03 11:33:47 -08:00
Kevin Decker e9f3a169c9 Merge pull request #698 from osiris43/master
Fix for issue #673
2014-01-03 10:53:18 -08:00
Brett Bim 70b27bcef6 Fix for issue #673 - Parser task did not execute correctly on windows environments because of forward/backward slash issues 2014-01-02 11:36:01 -06:00
Joe Wilm a1df862f06 Add koa-hbs to "handlebars in the wild" list 2014-01-01 20:21:27 -08:00
kpdecker 0c6829f8af v1.3.0 2014-01-01 22:10:31 -06:00
kpdecker 2b9f3c195f Update release notes 2014-01-01 22:09:50 -06:00
kpdecker f445b96cb7 Merge branch 'master' of github.com:wycats/handlebars.js 2014-01-01 19:42:16 -06:00
kpdecker e0d0ad5027 Merge branch 'compiler-options' of github.com:blakeembrey/handlebars.js into blakeembrey-compiler-options
Conflicts:
	lib/handlebars/compiler/javascript-compiler.js
2014-01-01 19:38:31 -06:00
Kevin Decker 3f71fde155 Merge pull request #696 from nateirwin/master
Fix for reserved keyword "default"
2014-01-01 17:17:19 -08:00
kpdecker 6e4e1f8404 Include line info in compiler thrown exceptions
Fixes #636
2014-01-01 19:14:51 -06:00
kpdecker 3c85720137 Remove duplication from generated subexpressions 2014-01-01 18:59:21 -06:00
kpdecker 4713abc8f1 Add subexpression benchmark 2014-01-01 18:15:39 -06:00
kpdecker e7e94dc697 Whitespace cleanup 2013-12-31 21:20:59 -06:00
kpdecker c1a93d33e7 Use literal for data lookup 2013-12-31 21:19:00 -06:00
kpdecker cd885bf855 Add stack handling sanity checks 2013-12-31 21:18:48 -06:00
kpdecker ddfe457abf Fix stack id "leak" on replaceStack 2013-12-31 21:17:50 -06:00
kpdecker f4d337d252 Fix incorrect stack pop when replacing literals 2013-12-31 21:17:16 -06:00
kpdecker cbfec5b9e9 Set laxbreak jshint flag 2013-12-31 20:25:46 -06:00
kpdecker af3358d195 Fix multiple hash handling in subexpressions 2013-12-31 16:10:51 -06:00
Nate Irwin 641358a905 Fix for reserved keyword "default" 2013-12-31 15:09:41 -07:00
kpdecker f2df220a1f Add location tracking to sexpr 2013-12-31 13:31:47 -06:00
Kevin Decker a2ca31bb19 Merge pull request #690 from machty/subsexpr
Added support for subexpressions
2013-12-30 16:09:41 -08:00
machty b09333db79 Added support for subexpressions
Handlebars now supports subexpressions.

    {{foo (bar 3)}}

Subexpressions are always evaluated as helpers; if
`3` were omitted from the above example, `bar`
would be invoked as a param-less helper, even
though a top-levell `{{bar}}` would be considered
ambiguous.

The return value of a subexpression helper is
passed in as a parameter of a parent subexpression
helper, even in string params mode. Their type,
as listed in `options.types` or `options.hashTypes`
in string params mode, is "sexpr".

The main conceptual change in the Handlebars code
is that there is a new AST.SexprNode that manages
the params/hash passed into a mustache, as well
as the logic that governs whether that mustache
is a helper invocation, property lookup, etc.
MustacheNode, which used to manage this stuff,
still exists, but only manages things like
white-space stripping and whether the mustache
is escaped or not. So, a MustacheNode _has_
a SexprNode.

The introduction of subexpressions is fully
backwards compatible, but a few things needed
to change about the compiled output of a template
in order to support subexpressions. The main one
is that the options hash is no longer stashed in
a local `options` var before being passed to
either the helper being invoked or the
`helperMissing` fallback. Rather, the options
object is inlined in these cases. This does
mean compiled template sizes will be a little
bit larger, even those that don't make use of
subexpressions, but shouldn't have any noticeable
impact on performance when actually rendering
templates as only one of these inlined objects
will actually get evaluated.
2013-12-30 19:07:04 -05:00
Kevin Decker ac98e7b177 Merge pull request #694 from blakeembrey/compile-env
Make the environment reusable
2013-12-29 15:23:47 -08:00
kpdecker 14d1d4270f Fix ProgramNode parameter handling under IE 2013-12-29 17:16:59 -06:00
Blake Embrey 150e55aa00 Pull options out from param setup to allow easier extension. 2013-12-28 22:31:45 -05:00
Blake Embrey 2f0c96b618 Make the environment reusable. 2013-12-28 21:35:40 -05:00
Yehuda Katz 6c2137a420 Merge pull request #692 from fivetanley/line-numbers
add line numbers to nodes when parsing
2013-12-28 17:12:25 -08:00
Stanley Stuart e1878050b5 add line numbers to nodes when parsing
closes #691
2013-12-28 18:55:36 -06:00
kpdecker 1c0614bd88 v1.2.1 2013-12-26 16:25:42 -06:00
kpdecker ba7a37a3b8 Update release notes 2013-12-26 16:25:17 -06:00
Kevin Decker 77fd7dcc1d Merge pull request #686 from wycats/amd-tests
Falsy AMD module names in version 1.2.0
2013-12-26 13:58:04 -08:00
kpdecker 7311ab0b3f Use quotes for reserved token name
Fixes test exec under IE
2013-12-26 15:39:11 -06:00
kpdecker 4160ff3ee2 Revert unused flag addition 2013-12-26 15:26:12 -06:00
kpdecker 7151d15abb Add AMD tests to sauce tests 2013-12-26 15:20:37 -06:00
kpdecker 19f443f68e Use latest jshint 2013-12-26 15:12:10 -06:00
Kevin Decker 9f1b3bcea0 Merge pull request #685 from blakeembrey/dombars
Add dombars to the projects list
2013-12-25 10:13:13 -08:00
Kevin Decker 2dae244185 Merge pull request #684 from blakeembrey/javascript-variable
Allow any number of trailing characters for valid JavaScript variable
2013-12-25 10:12:11 -08:00
Blake Embrey c62ce32cc9 Add dombars to the projects list. 2013-12-24 16:21:28 -05:00
Blake Embrey f3a90812a6 Allow any number of trailing characters. 2013-12-24 16:14:57 -05:00
kpdecker 096b8ccd2e v1.2.0 2013-12-23 21:39:46 -06:00
kpdecker 923993dfb1 Update release notes 2013-12-23 21:39:23 -06:00
kpdecker fcf4e4ef0e Update release documentation 2013-12-23 21:30:34 -06:00
kpdecker ae1795f82c Update sauce tests for supported versions 2013-12-23 21:24:11 -06:00
kpdecker 2666553383 Cleanup jshint globals a bit 2013-12-23 21:16:25 -06:00
kpdecker 15af03c8bf Remove unused var 2013-12-23 21:16:14 -06:00
kpdecker 97c7d65931 Do not minimize multiple times 2013-12-23 21:16:07 -06:00
kpdecker bbc7c7d080 Expose compilerInfo and checkRevision as APIs
Fixes #656
2013-12-23 21:00:59 -06:00
kpdecker 1a751b2f6e Add JavascriptCompiler public API tests 2013-12-23 20:59:16 -06:00
kpdecker abe9c82e75 Use env.VM to lookup runtime methods
Allows for overrides by 3rd parties

Fixes #679
2013-12-23 19:53:11 -06:00
kpdecker 956ac95e7a Add browserify runtime export
Fixes #668
2013-12-23 19:51:10 -06:00
kpdecker 40e1837b14 Merge branch 'fix-escapes' of github.com:dmarcotte/handlebars.js into dmarcotte-fix-escapes
Conflicts:
	spec/tokenizer.js
2013-12-23 19:22:30 -06:00
kpdecker ddea5be2a4 Add AST test coverage for more complex paths 2013-12-23 19:02:45 -06:00
kpdecker b4968bb8d4 Fix handling of boolean escape in MustacheNode
Fixes issue with Ember compatibility due to direct instantiation of MustacheNode.
2013-12-23 19:02:24 -06:00
Kevin Decker ca8e34c94d Merge pull request #641 from wycats/ember-testing
Document ember testing process
2013-12-23 16:13:22 -08:00
kpdecker 4a94340f42 Add docs on testing ember integration 2013-12-23 18:12:14 -06:00
kpdecker 7d69becd2e Add notes on bower install
Fixes #655
2013-12-23 15:50:07 -06:00
kpdecker 1a9b5d4ac6 Add test case to cover #676
Fixes #676
2013-12-23 15:42:38 -06:00
kpdecker bdc0e6507e Provide default sort for builds link 2013-12-23 15:34:40 -06:00
kpdecker 93fb25c702 Handle empty responses from partials
Fixes #675
2013-12-23 15:33:33 -06:00
kpdecker 23d41e5617 Use watch atBegin command to handle failing tests 2013-12-23 14:26:56 -06:00
kpdecker d62620a282 Implement grunt dev task 2013-12-23 13:13:25 -06:00
Kevin Decker 62fdd541f5 Merge pull request #681 from wycats/sauce-tests
Adds in-browser testing and Saucelabs CI
2013-12-23 11:09:57 -08:00
kpdecker 7f53c917d9 Skip leak check under FF 2013-12-23 12:32:48 -06:00
kpdecker 015eba6687 Hide success messages when running in sauce
This should help debug the firefox issues that only occur when executing against sauce.
2013-12-23 11:57:11 -06:00
kpdecker 5b8b54b774 Add travis build caching 2013-12-23 03:20:13 -06:00
kpdecker efcedf2f24 Optimize travis build with publish option 2013-12-23 03:12:03 -06:00
kpdecker 512daa3189 Create matrix target for 0.10 only 2013-12-23 02:58:02 -06:00
kpdecker ad3727b3fc (Attempt to) Limit sauce tests to one travis build 2013-12-23 02:52:46 -06:00
kpdecker e2a81fdd60 Add selenium badge 2013-12-23 02:46:35 -06:00
kpdecker fe7bc0d4bd Add sauce labs testing support 2013-12-23 02:32:46 -06:00
kpdecker 9ad8b86ece Concat tests together for inbrowser exec 2013-12-23 02:19:09 -06:00
kpdecker 96b42dedea Fix tokenizer tests under IE 2013-12-23 02:19:09 -06:00
kpdecker 4942324250 Move away from should asserts to internal
This is needed as neither Sinon nor Chai support in-browser testing under IE.
2013-12-23 02:19:09 -06:00
kpdecker 0cf5657c43 Use shouldThrow helper for test asserts 2013-12-23 02:19:09 -06:00
kpdecker 3daef9d308 Use charAt rather than string index
Older versions of IE do not support [] access to string contents so charAt must be used.

Fixes #677
2013-12-23 02:18:57 -06:00
kpdecker 7f0ded4926 Relax packager dependency 2013-12-22 18:50:18 -06:00
kpdecker 1041c1d533 Add tests for object @index and @first handling 2013-12-22 18:46:13 -06:00
kpdecker f06a9dc1f0 Use strict comparison for first 2013-12-22 18:45:57 -06:00
kpdecker 45ab2bb218 Merge branch 'patch-1' of github.com:cgp/handlebars.js into cgp-patch-1 2013-12-22 18:27:10 -06:00
kpdecker f17cb3ecac Run jshint on output
Allows us to execute jshint in non-forced mode.
2013-12-01 15:40:08 -06:00
kpdecker 86974b2660 jshint 2013-12-01 14:59:44 -06:00
kpdecker 57b4ef08b6 Use module packager for all transpile tasks 2013-12-01 14:59:38 -06:00
kpdecker cc16bc47dd Add missing semicolon 2013-12-01 11:37:32 -06:00
kpdecker 078c1eecba Export AST as an object rather than module
The parser expects the AST object to be mutable, which modules are not.
2013-12-01 11:37:25 -06:00
kpdecker eb53f2e844 Allow extend to work with non-prototyped objects
ES6 modules do not extend the Object prototype so this blows up under the latest version of the transpiler.
2013-12-01 11:36:28 -06:00
Chris Pall e8954b3488 Update base.js
Give users the index for properties. When I am rendering a radio button I use key-value pairs, but I can't use either as unique identifiers because they likely contain invalid identifier characters. I added "first" as an index as well, but have no particular use case for first. Since there is no way to detect "last", I didn't add that property.
2013-11-22 00:41:25 -05:00
Kevin Decker 20b9c3829e Merge pull request #653 from k-j-kleist/patch-1
Update README.markdown
2013-11-20 09:35:53 -08:00
Kevin Decker 709153f7f5 Merge pull request #650 from thomasboyt/patch-1
Handlebars is MIT-licensed
2013-11-20 09:34:25 -08:00
Kevin Decker d5cc3fbcf1 Merge pull request #657 from chrishoage/master
Fixes issue where cli compiles non handlebars templates
2013-11-20 09:32:48 -08:00
choage d3cff5c1cd Fixes issue where cli compiles non handlebars templates 2013-11-17 16:35:01 -08:00
Karl Johan Kleist 83106e7a5e Update README.markdown
Added "Ghost" (Just a blogging platform) to "Handlebars in the Wild".
2013-11-12 10:41:56 +01:00
Thomas Boyt 525e58d318 Handlebars is MIT-licensed
The package.json list Handlebars as having a BSD license, but the readme says it's MIT licensed
2013-11-08 11:48:31 -05:00
Daniel Marcotte 9d353bd3dd Fix "\\{{" immediately following "\{{"
Escaped-escape mustaches ("\\{{") immediately following escaped
mustaches ("\{{") were being handled incorrectly.

Fix the lookahead to make sure yytext still contains the appropriate
slashes when we pop out of <emu> so they can be handled consistently
by the initial state.
2013-11-06 08:20:49 -08:00
kpdecker 47d13cb23c v1.1.2 2013-11-05 18:10:06 -06:00
kpdecker 7c13753bb5 Update release notes 2013-11-05 18:09:26 -06:00
kpdecker affbcbb79e Unify isArray/isFunction/toString implementations
Restores Array.isArray polyfill for all use cases.

Fixes #645
2013-11-05 18:07:33 -06:00
kpdecker 96a45a4a96 Add simple binary utility tests 2013-11-05 18:02:25 -06:00
kpdecker 6f6eb89bd8 Use handlebars runtime from precompiled amd files
Fixes #644
2013-11-05 18:02:05 -06:00
kpdecker eea708a18d Fix empty string compilation 2013-11-04 22:11:53 -06:00
Stefan Penner 508bb2d55d local grunt-cli 2013-11-04 21:18:57 -05:00
kpdecker 09cdc19a21 v1.1.1 2013-11-04 10:48:59 -06:00
kpdecker 2cb61c9d5f Update release notes 2013-11-04 10:48:12 -06:00
kpdecker 986d6f4096 Fix CLI library loading
Fixes #642
2013-11-04 10:46:50 -06:00
kpdecker 1e20373428 Document release process
Fixes #546
Fixes #640
2013-11-04 00:26:03 -06:00
kpdecker 17ba258355 Fix release notes link 2013-11-03 23:43:45 -06:00
89 changed files with 9157 additions and 1704 deletions
+2
View File
@@ -4,7 +4,9 @@ vendor
lib/handlebars/compiler/parser.js
/dist/
/tmp/
/coverage/
node_modules
*.sublime-project
*.sublime-workspace
npm-debug.log
sauce_connect.log*
+3
View File
@@ -0,0 +1,3 @@
[submodule "spec/mustache"]
path = spec/mustache
url = git://github.com/mustache/spec.git
+2
View File
@@ -0,0 +1,2 @@
instrumentation:
excludes: ['**/spec/**']
+5 -10
View File
@@ -1,14 +1,6 @@
{
"predef": [
"console",
"Ember",
"DS",
"Handlebars",
"Metamorph",
"ember_assert",
"ember_warn",
"ember_deprecate",
"ember_deprecateFunc",
"require",
"suite",
"equal",
@@ -22,10 +14,12 @@
"ok",
"strictEqual",
"module",
"define",
"describe",
"it",
"afterEach"
"afterEach",
"beforeEach"
],
"node" : true,
@@ -41,7 +35,7 @@
"evil": true,
"forin": false,
"immed": false,
"laxbreak": false,
"laxbreak": true,
"newcap": true,
"noarg": true,
"noempty": false,
@@ -51,6 +45,7 @@
"plusplus": false,
"regexp": false,
"undef": true,
"unused": true,
"sub": true,
"strict": false,
"white": false
+2
View File
@@ -13,10 +13,12 @@ Gruntfile.js
bench/*
configurations/*
components/*
coverage/*
dist/cdnjs/*
dist/components/*
spec/*
src/*
tasks/*
tmp/*
publish/*
vendor/*
+14 -18
View File
@@ -1,27 +1,23 @@
language: node_js
node_js:
- "0.8"
- "0.10"
before_install:
- npm install -g grunt-cli
- npm install -g grunt-cli
script:
- grunt --stack default metrics publish:latest
- grunt --stack travis
email:
on_failure: change
on_success: never
env:
global:
- S3_BUCKET_NAME=builds.handlebarsjs.com
- secure: ! 'PJaukuvkBBsSDOqbIcNSSMgb96VVEaIt/eq9GPjXPeFbSd3hXgwhwVE62Lrq
tJO8BaUfX+PzpiQjEl4D5/KBmvlFZ057Hqmy0zmPOT5mDZfJe8Ja5zyvTMb+
KkCWN/tjAp8kawHojE04pn6jIpPdwXFnAYwPhaHbATFrmdt9fdg='
- secure: ! 'mBcGL2tnmiRujJdV/4fxrVd8E8wn6AW9IQKVcMv8tvOc7i5dOzZ39rpBKLuT
MRXDtMV1LyLiuKYb1pHj1IyeadEahcLYFfGygF4LG7Yzp4NWHtRzQ7Q8LXaJ
V7dXDboYCFkn2a8/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=
cache:
directories:
- node_modules
+80
View File
@@ -0,0 +1,80 @@
# How to Contribute
## Reporting Issues
Please see our [FAQ](https://github.com/wycats/handlebars.js/blob/master/FAQ.md) for common issues that people run into.
Should you run into other issues with the project, please don't hesitate to let us know by filing an [issue][issue]! In general we are going to ask for an example of the problem failing, which can be as simple as a jsfiddle/jsbin/etc. We've put together a jsfiddle [template][jsfiddle] to ease this. (We will keep this link up to date as new releases occur, so feel free to check back here)
Pull requests containing only failing thats demonstrating the issue are welcomed and this also helps ensure that your issue won't regress in the future once it's fixed.
Documentation issues on the handlebarsjs.com site should be reported on [handlebars-site](https://github.com/wycats/handlebars-site).
## Pull Requests
We also accept [pull requests][pull-request]!
Generally we like to see pull requests that
- Maintain the existing code style
- Are focused on a single change (i.e. avoid large refactoring or style adjustments in untouched code if not the primary goal of the pull request)
- Have [good commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
- Have tests
- Don't significantly decrease the current code coverage (see coverage/lcov-report/index.html)
## Building
To build Handlebars.js you'll need a few things installed.
* Node.js
* [Grunt](http://gruntjs.com/getting-started)
Before building, you need to make sure that the Git submodule `spec/mustache` is included (i.e. the directory `spec/mustache` should not be empty). To include it, if using Git version 1.6.5 or newer, use `git clone --recursive` rather than `git clone`. Or, if you already cloned without `--recursive`, use `git submodule update --init`.
Project dependencies may be installed via `npm install`.
To build Handlebars.js from scratch, you'll want to run `grunt`
in the root of the project. That will build Handlebars and output the
results to the dist/ folder. To re-run tests, run `grunt test` or `npm test`.
You can also run our set of benchmarks with `grunt bench`.
The `grunt dev` implements watching for tests and allows for in browser testing at `http://localhost:9999/spec/`.
If you notice any problems, please report them to the GitHub issue tracker at
[http://github.com/wycats/handlebars.js/issues](http://github.com/wycats/handlebars.js/issues).
## Ember testing
The current ember distribution should be tested as part of the handlebars release process. This requires building the `handlebars-source` gem locally and then executing the ember test script.
```sh
npm link
grunt build release
cp dist/*.js $emberRepoDir/bower_components/handlebars/
cd $emberRepoDir
npm link handlebars
npm test
```
## Releasing
Handlebars utilizes the [release yeoman generator][generator-release] to perform most release tasks.
A full release may be completed with the following:
```
yo release
npm publish
yo release:publish components handlebars.js dist/components/
cd dist/components/
gem build handlebars-source.gemspec
gem push handlebars-source-*.gem
```
After this point the handlebars site needs to be updated to point to the new version numbers. The jsfiddle link should be updated to point to the most recent distribution for all instances in our documentation.
[generator-release]: https://github.com/walmartlabs/generator-release
[pull-request]: https://github.com/wycats/handlebars.js/pull/new/master
[issue]: https://github.com/wycats/handlebars.js/issues/new
[jsfiddle]: http://jsfiddle.net/9D88g/26/
+60
View File
@@ -0,0 +1,60 @@
# Frequently Asked Questions
1. How can I file a bug report:
See our guidelines on [reporting issues](https://github.com/wycats/handlebars.js/blob/master/CONTRIBUTING.md#reporting-issues).
1. Why isn't my Mustache template working?
Handlebars deviates from Mustache slightly on a few behaviors. These variations are documented in our [readme](https://github.com/wycats/handlebars.js#differences-between-handlebarsjs-and-mustache).
1. Why is it slower when compiling?
The Handlebars compiler must parse the template and construct a JavaScript program which can then be run. Under some environments such as older mobile devices this can have a performance impact which can be avoided by precompiling. Generally it's recommended that precompilation and the runtime library be used on all clients.
1. Why doesn't this work with Content Security Policy restrictions?
When not using the precompiler, Handlebars generates a dynamic function for each template which can cause issues with pages that have enabled Content Policy. It's recommended that templates are precompiled or the `unsafe-eval` policy is enabled for sites that must generate dynamic templates at runtime.
1. How can I include script tags in my template?
If loading the template via an inlined `<script type="text/x-handlebars">` tag then you may need to break up the script tag with an empty comment to avoid browser parser errors:
```html
<script type="text/x-handlebars">
foo
<scr{{!}}ipt src="bar"></scr{{!}}ipt>
</script>
```
It's generally recommended that templates are served through external, precompiled, files, which do not suffer from this issue.
1. Why are my precompiled scripts throwing exceptions?
When using the precompiler, it's important that a supporting version of the Handlebars runtime be loaded on the target page. In version 1.x there were rudimentary checks to compare the version but these did not always work. This is fixed under 2.x but the version checking does not work between these two versions. If you see unexpected errors such as `undefined is not a function` or similar, please verify that the same version is being used for both the precompiler and the client. This can be checked via:
```sh
handlebars --version
```
If using the integrated precompiler and
```javascript
console.log(Handlebars.VERSION);
```
On the client side.
We include the built client libraries in the npm package for those who want to be certain that they are using the same client libraries as the compiler.
Should these match, please file an issue with us, per our [issue filing guidelines](https://github.com/wycats/handlebars.js/blob/master/CONTRIBUTING.md#reporting-issues).
1. Why doesn't IE like the `default` name in the AMD module?
Some browsers such as particular versions of IE treat `default` as a reserved word in JavaScript source files. To safely use this you need to reference this via the `Handlebars['default']` lookup method. This is an unfortunate side effect of the shims necessary to backport the Handlebars ES6 code to all current browsers.
1. How do I load the runtime library when using AMD?
There are two options for loading under AMD environments. The first is to use the `handlebars.runtime.amd.js` file. This may require a [path mapping](https://github.com/wycats/handlebars.js/blob/master/spec/amd-runtime.html#L31) as well as access via the `default` field.
The other option is to load the `handlebars.runtime.js` UMD build, which might not require path configuration and exposes the library as both the module root and the `default` field for compatibility.
If not using ES6 transpilers or accessing submodules in the build the former option should be sufficient for most use cases.
+92 -47
View File
@@ -7,15 +7,14 @@ module.exports = function(grunt) {
jshint: {
options: {
jshintrc: '.jshintrc',
force: true
jshintrc: '.jshintrc'
},
files: [
'lib/**/!(parser).js'
'dist/cjs/**/!(*.min|parser).js'
]
},
clean: ["dist", "lib/handlebars/compiler/parser.js"],
clean: ['tmp', 'dist', 'lib/handlebars/compiler/parser.js'],
copy: {
dist: {
@@ -42,9 +41,20 @@ module.exports = function(grunt) {
}
},
transpile: {
packager: {
global: {
type: 'umd',
export: 'Handlebars',
files: [{
cwd: 'lib/',
expand: true,
src: ['handlebars*.js'],
dest: 'dist/'
}]
},
amd: {
type: "amd",
type: 'amd',
anonymous: true,
files: [{
expand: true,
@@ -64,21 +74,6 @@ module.exports = function(grunt) {
}]
}
},
packager: {
options: {
export: 'Handlebars'
},
global: {
files: [{
cwd: 'lib/',
expand: true,
src: ['handlebars*.js'],
dest: 'dist/'
}]
}
},
requirejs: {
options: {
optimize: "none",
@@ -108,57 +103,107 @@ module.exports = function(grunt) {
files: [{
cwd: 'dist/',
expand: true,
src: ['handlebars*.js'],
src: ['handlebars*.js', '!*.min.js'],
dest: 'dist/',
rename: function(dest, src) {
return dest + src.replace(/\.js$/, '.min.js');
}
}]
}
},
concat: {
tests: {
src: ['spec/!(require).js'],
dest: 'tmp/tests.js'
}
},
connect: {
server: {
options: {
base: '.',
hostname: '*',
port: 9999
}
}
},
'saucelabs-mocha': {
all: {
options: {
build: process.env.TRAVIS_JOB_ID,
urls: ['http://localhost:9999/spec/?headless=true', 'http://localhost:9999/spec/amd.html?headless=true'],
detailedError: true,
concurrency: 2,
browsers: [
{browserName: 'chrome'},
{browserName: 'firefox'},
{browserName: 'safari', version: 7, platform: 'OS X 10.9'},
{browserName: 'safari', version: 6, platform: 'OS X 10.8'},
{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'}
]
}
},
sanity: {
options: {
build: process.env.TRAVIS_JOB_ID,
urls: ['http://localhost:9999/spec/umd.html?headless=true', 'http://localhost:9999/spec/amd-runtime.html?headless=true', 'http://localhost:9999/spec/umd-runtime.html?headless=true'],
detailedError: true,
concurrency: 2,
browsers: [
{browserName: 'chrome'}
]
}
}
},
watch: {
scripts: {
options: {
atBegin: true
},
files: ['src/*', 'lib/**/*.js', 'spec/**/*.js'],
tasks: ['build', 'amd', 'tests', 'test']
}
}
});
// Build a new version of the library
this.registerTask('build', "Builds a distributable version of the current project", [
'jshint',
'clean',
'parser',
'node',
'globals']);
'globals',
'jshint']);
this.registerTask('amd', ['transpile:amd', 'requirejs']);
this.registerTask('node', ['transpile:cjs']);
this.registerTask('globals', ['packager-fork']);
this.registerTask('amd', ['packager:amd', 'requirejs']);
this.registerTask('node', ['packager:cjs']);
this.registerTask('globals', ['packager:global']);
this.registerTask('tests', ['concat:tests']);
this.registerTask('release', 'Build final packages', ['amd', 'uglify', 'copy:dist', 'copy:components', 'copy:cdnjs']);
this.registerTask('release', 'Build final packages', ['amd', 'jshint', 'uglify', 'copy:dist', 'copy:components', 'copy:cdnjs']);
// Load tasks from npm
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-es6-module-transpiler');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-saucelabs');
grunt.loadNpmTasks('es6-module-packager');
grunt.task.loadTasks('tasks');
grunt.registerTask('packager-fork', function() {
// Allows us to run the packager task out of process to work around the multiple
// traceur exec issues
grunt.util.spawn({grunt: true, args: ['--stack', 'packager'], opts: {stdio: 'inherit'}}, this.async());
});
grunt.registerTask('test', function() {
var done = this.async();
var runner = childProcess.fork('./spec/env/runner', [], {stdio: 'inherit'});
runner.on('close', function(code) {
if (code != 0) {
grunt.fatal(code + ' tests failed');
}
done();
});
});
grunt.registerTask('bench', ['metrics']);
grunt.registerTask('sauce', process.env.SAUCE_USERNAME ? ['tests', 'connect', 'saucelabs-mocha'] : []);
grunt.registerTask('default', ['build', 'test', 'release']);
grunt.registerTask('travis', process.env.PUBLISH ? ['default', 'sauce', 'metrics', 'publish:latest'] : ['default']);
grunt.registerTask('dev', ['clean', 'connect', 'watch']);
grunt.registerTask('default', ['clean', 'build', 'test', 'release']);
};
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (C) 2011 by Yehuda Katz
Copyright (C) 2011-2014 by Yehuda Katz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+65 -46
View File
@@ -1,5 +1,5 @@
[![Build Status](https://travis-ci.org/wycats/handlebars.js.png?branch=master)](https://travis-ci.org/wycats/handlebars.js)
[![Travis Build Status](https://img.shields.io/travis/wycats/handlebars.js/master.svg)](https://travis-ci.org/wycats/handlebars.js)
[![Selenium Test Status](https://saucelabs.com/buildstatus/handlebars)](https://saucelabs.com/u/handlebars)
Handlebars.js
=============
@@ -14,9 +14,9 @@ Checkout the official Handlebars docs site at
Installing
----------
Installing Handlebars is easy. Simply download the package [from the
official site](http://handlebarsjs.com/) and add it to your web pages
(you should usually use the most recent version).
Installing Handlebars is easy. Simply download the package [from the official site](http://handlebarsjs.com/) or the [bower repository][bower-repo] and add it to your web pages (you should usually use the most recent version).
For web browsers, a free CDN is available at [jsDelivr](http://www.jsdelivr.com/#!handlebarsjs). Advanced usage, such as [version aliasing & concocting](https://github.com/jsdelivr/jsdelivr#usage), is available.
Alternatively, if you prefer having the latest version of handlebars from
the 'master' branch, passing builds of the 'master' branch are automatically
@@ -67,11 +67,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);
@@ -110,7 +110,7 @@ templates easier and also changes a tiny detail of how partials work.
### Paths
Handlebars.js supports an extended expression syntax that we call paths.
Paths are made up of typical expressions and . characters. Expressions
Paths are made up of typical expressions and `.` characters. Expressions
allow you to not only display data from the current context, but to
display data from contexts that are descendants and ancestors of the
current context.
@@ -134,7 +134,7 @@ into the person object you could still display the company's name with
an expression like `{{../company.name}}`, so:
```
{{#person}}{{name}} - {{../company.name}}{{/person}}
{{#with person}}{{name}} - {{../company.name}}{{/with}}
```
would render:
@@ -197,7 +197,7 @@ template(data);
```
Whenever the block helper is called it is given one or more parameters,
any arguments that are passed in the helper in the call and an `options`
any arguments that are passed into the helper in the call, and an `options`
object containing the `fn` function which executes the block's child.
The block's current context may be accessed through `this`.
@@ -236,6 +236,35 @@ template(data);
// </ul>
```
Partials can also accept parameters
```js
var source = "<div>{{> roster rosterProperties people=listOfPeople}}</div>";
Handlebars.registerPartial('roster', '<h2>{{rosterName}}</h2>{{#people}}<span>{{id}}: {{name}}</span>{{/people}}')
var template = Handlebars.compile(source);
var data = {
"listOfPeople": [
{ "name": "Alan", "id": 1 },
{ "name": "Yehuda", "id": 2 }
],
"rosterProperties": {
"rosterName": "Cool People"
}
};
template(data);
// Should render:
// <div>
// <h2>Cool People</h2>
// <span>1: Alan</span>
// <span>2: Yehuda</span>
// </div>
```
### Comments
You can add comments to your templates with the following syntax:
@@ -254,6 +283,14 @@ You can also use real html comments if you want them to end up in the output.
```
### Compatibility
There are a few Mustache behaviors that Handlebars does not implement.
- Handlebars deviates from Mustache slightly in that it does not perform recursive lookup by default. The compile time `compat` flag must be set to enable this functionality. Users should note that there is a performance cost for enabling this flag. The exact cost varies by template, but it's recommended that performance sensitive operations should avoid this mode and instead opt for explicit path references.
- The optional Mustache-style lambdas are not supported. Instead Handlebars provides it's own lambda resolution that follows the behaviors of helpers.
- Alternative delimeters are not supported.
Precompiling Templates
----------------------
@@ -293,9 +330,8 @@ name sans the extension. These templates may be executed in the same
manner as templates.
If using the simple mode the precompiler will generate a single
javascript method. To execute this method it must be passed to the using
the `Handlebars.template` method and the resulting object may be as
normal.
javascript method. To execute this method it must be passed to
the `Handlebars.template` method and the resulting object may be used as normal.
### Optimizations
@@ -323,7 +359,9 @@ 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)
Performance
-----------
@@ -336,13 +374,7 @@ does have some big performance advantages. Justin Marney, a.k.a.
[gotascii](http://github.com/gotascii), confirmed that with an
[independent test](http://sorescode.com/2010/09/12/benchmarks.html). The
rewritten Handlebars (current version) is faster than the old version,
and we will have some benchmarks in the near future.
Building
--------
To build handlebars, just run `grunt build`, and the build will output to the `dist` directory.
with many [performance tests](https://travis-ci.org/wycats/handlebars.js/builds/33392182#L538) being 5 to 7 times faster than the Mustache equivalent.
Upgrading
@@ -352,8 +384,9 @@ See [release-notes.md](https://github.com/wycats/handlebars.js/blob/master/relea
Known Issues
------------
* Handlebars.js can be cryptic when there's an error while rendering.
* Using a variable, helper, or partial named `class` causes errors in IE browsers. (Instead, use `className`)
See [FAQ.md](https://github.com/wycats/handlebars.js/blob/master/FAQ.md) for known issues and common pitfalls.
Handlebars in the Wild
----------------------
@@ -362,14 +395,18 @@ Handlebars in the Wild
and [@doowb](https://github.com/doowb), is a static site generator that uses Handlebars.js
as its template engine.
* [CoSchedule](http://coschedule.com) An editorial calendar for WordPress that uses Handlebars.js
* [dashbars](https://github.com/pismute/dashbars) A modern helper library for Handlebars.js.
* [Ember.js](http://www.emberjs.com) makes Handlebars.js the primary way to
structure your views, also with automatic data binding support.
* [Ghost](https://ghost.org/) Just a blogging platform.
* [handlebars_assets](http://github.com/leshill/handlebars_assets): A Rails Asset Pipeline gem
from Les Hill (@leshill).
* [handlebars-helpers](https://github.com/assemble/handlebars-helpers) is an extensive library
with 100+ handlebars helpers.
* [hbs](http://github.com/donpark/hbs): An Express.js view engine adapter for Handlebars.js,
from Don Park.
* [koa-hbs](https://github.com/jwilm/koa-hbs): [koa](https://github.com/koajs/koa) generator based
renderer for Handlebars.js.
* [jblotus](http://github.com/jblotus) created [http://tryhandlebarsjs.com](http://tryhandlebarsjs.com)
for anyone who would like to try out Handlebars.js in their browser.
* [jQuery plugin](http://71104.github.io/jquery-handlebars/): allows you to use
@@ -382,37 +419,19 @@ Handlebars in the Wild
templating engine, extending it with automatic data binding support.
* [YUI](http://yuilibrary.com/yui/docs/handlebars/) implements a port of handlebars
* [Swag](https://github.com/elving/swag) by [@elving](https://github.com/elving) is a growing collection of helpers for handlebars.js. Give your handlebars.js templates some swag son!
* [DOMBars](https://github.com/blakeembrey/dombars) is a DOM-based templating engine built on the Handlebars parser and runtime
External Resources
------------------
* [Gist about Synchronous and asynchronous loading of external handlebars templates](https://gist.github.com/2287070)
Have a project using Handlebars? Send us a [pull request](https://github.com/wycats/handlebars.js/pull/new/master)!
Helping Out
-----------
To build Handlebars.js you'll need a few things installed.
* Node.js
* [Grunt](http://gruntjs.com/getting-started)
Project dependencies may be installed via `npm install`.
To build Handlebars.js from scratch, you'll want to run `grunt`
in the root of the project. That will build Handlebars and output the
results to the dist/ folder. To re-run tests, run `grunt test` or `npm test`.
You can also run our set of benchmarks with `grunt bench`.
If you notice any problems, please report them to the GitHub issue tracker at
[http://github.com/wycats/handlebars.js/issues](http://github.com/wycats/handlebars.js/issues).
Feel free to contact commondream or wycats through GitHub with any other
questions or feature requests. To submit changes fork the project and
send a pull request.
Have a project using Handlebars? Send us a [pull request][pull-request]!
License
-------
Handlebars.js is released under the MIT license.
[builds-page]: http://builds.handlebarsjs.com.s3.amazonaws.com/index.html
[bower-repo]: https://github.com/components/handlebars.js
[builds-page]: http://builds.handlebarsjs.com.s3.amazonaws.com/bucket-listing.html?sort=lastmod&sortdir=desc
[pull-request]: https://github.com/wycats/handlebars.js/pull/new/master
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
context: { names: [{name: "Moe"}, {name: "Larry"}, {name: "Curly"}, {name: "Shemp"}], foo: 'bar' },
handlebars: "{{#each names}}{{../foo}}{{/each}}",
mustache: "{{#names}}{{foo}}{{/names}}",
eco: "<% for item in @names: %><%= @foo %><% end %>"
};
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
context: { names: [{bat: 'foo', name: ["Moe"]}, {bat: 'foo', name: ["Larry"]}, {bat: 'foo', name: ["Curly"]}, {bat: 'foo', name: ["Shemp"]}], foo: 'bar' },
handlebars: "{{#each names}}{{#each name}}{{../bat}}{{../../foo}}{{/each}}{{/each}}",
mustache: "{{#names}}{{#name}}{{bat}}{{foo}}{{/name}}{{/names}}",
eco: "<% for item in @names: %><% for child in item.name: %><%= item.bat %><%= @foo %><% end %><% end %>"
};
+5 -5
View File
@@ -1,7 +1,7 @@
module.exports = {
context: { person: { name: "Larry", age: 45 } },
handlebars: "{{person.name}}{{person.age}}{{person.foo}}{{animal.age}}",
dust: "{person.name}{person.age}{person.foo}{animal.age}",
eco: "<%= @person.name %><%= @person.age %><%= @person.foo %><% if @animal: %><%= @animal.age %><% end %>",
mustache: "{{person.name}}{{person.age}}{{person.foo}}{{animal.age}}"
context: { person: { name: {bar: {baz: "Larry"}}, age: 45 } },
handlebars: "{{person.name.bar.baz}}{{person.age}}{{person.foo}}{{animal.age}}",
dust: "{person.name.bar.baz}{person.age}{person.foo}{animal.age}",
eco: "<%= @person.name.bar.baz %><%= @person.age %><%= @person.foo %><% if @animal: %><%= @animal.age %><% end %>",
mustache: "{{person.name.bar.baz}}{{person.age}}{{person.foo}}{{animal.age}}"
};
+14
View File
@@ -0,0 +1,14 @@
module.exports = {
helpers: {
echo: function(value) {
return 'foo ' + value;
},
header: function() {
return "Colors";
}
},
handlebars: "{{echo (header)}}",
eco: "<%= @echo(@header()) %>"
};
module.exports.context = module.exports.helpers;
+8
View File
@@ -28,11 +28,13 @@ function makeSuite(bench, name, template, handlebarsOnly) {
partials = template.partials,
handlebarsOut,
compatOut,
dustOut,
ecoOut,
mustacheOut;
var handlebar = Handlebars.compile(template.handlebars, {data: false}),
compat = Handlebars.compile(template.handlebars, {data: false, compat: true}),
options = {helpers: template.helpers};
_.each(template.partials && template.partials.handlebars, function(partial, name) {
Handlebars.registerPartial(name, Handlebars.compile(partial, {data: false}));
@@ -43,6 +45,11 @@ function makeSuite(bench, name, template, handlebarsOnly) {
handlebar(context, options);
});
compatOut = compat(context, options);
bench("compat", function() {
compat(context, options);
});
if (handlebarsOnly) {
return;
}
@@ -107,6 +114,7 @@ function makeSuite(bench, name, template, handlebarsOnly) {
}
}
compare(compatOut, 'compat');
compare(dustOut, 'dust');
compare(ecoOut, 'eco');
compare(mustacheOut, 'mustache');
+25 -136
View File
@@ -1,12 +1,16 @@
#!/usr/bin/env node
var optimist = require('optimist')
.usage('Precompile handlebar templates.\nUsage: $0 template...', {
.usage('Precompile handlebar templates.\nUsage: $0 [template|directory]...', {
'f': {
'type': 'string',
'description': 'Output File',
'alias': 'output'
},
'map': {
'type': 'string',
'description': 'Source Map File'
},
'a': {
'type': 'boolean',
'description': 'Exports amd style (require.js)',
@@ -22,7 +26,7 @@ var optimist = require('optimist')
'type': 'string',
'description': 'Path to handlebar.js (only valid for amd-style)',
'alias': 'handlebarPath',
'default': ''
'default': ''
},
'k': {
'type': 'string',
@@ -75,148 +79,33 @@ 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'
},
'help': {
'type': 'boolean',
'description': 'Outputs this message'
}
})
.check(function(argv) {
var template = [0];
if (!argv._.length) {
throw 'Must define at least one template or directory.';
}
argv._.forEach(function(template) {
try {
fs.statSync(template);
} catch (err) {
throw 'Unable to open template file "' + template + '"';
}
});
})
.check(function(argv) {
if (argv.simple && argv.min) {
throw 'Unable to minimze simple output';
}
if (argv.simple && (argv._.length !== 1 || fs.statSync(argv._[0]).isDirectory())) {
throw 'Unable to output multiple templates in simple mode';
if (argv.version) {
return;
}
});
var fs = require('fs'),
handlebars = require('../lib/handlebars'),
basename = require('path').basename,
uglify = require('uglify-js');
var argv = optimist.argv,
template = argv._[0];
var argv = optimist.argv;
argv.templates = argv._;
delete argv._;
// Convert the known list into a hash
var known = {};
if (argv.known && !Array.isArray(argv.known)) {
argv.known = [argv.known];
}
if (argv.known) {
for (var i = 0, len = argv.known.length; i < len; i++) {
known[argv.known[i]] = true;
}
if (argv.help || (!argv.templates.length && !argv.version)) {
optimist.showHelp();
return;
}
// Build file extension pattern
var extension = argv.extension.replace(/[\\^$*+?.():=!|{}\-\[\]]/g, function(arg) { return '\\' + arg; });
extension = new RegExp('\\.' + extension + '$');
var output = [];
if (!argv.simple) {
if (argv.amd) {
output.push('define([\'' + argv.handlebarPath + 'handlebars\'], function(Handlebars) {\n Handlebars = Handlebars["default"];');
} else if (argv.commonjs) {
output.push('var Handlebars = require("' + argv.commonjs + '");');
} else {
output.push('(function() {\n');
}
output.push(' var template = Handlebars.template, templates = ');
output.push(argv.namespace);
output.push(' = ');
output.push(argv.namespace);
output.push(' || {};\n');
}
function processTemplate(template, root) {
var path = template,
stat = fs.statSync(path);
if (stat.isDirectory()) {
fs.readdirSync(template).map(function(file) {
var path = template + '/' + file;
if (extension.test(path) || fs.statSync(path).isDirectory()) {
processTemplate(path, root || template);
}
});
} else {
var data = fs.readFileSync(path, 'utf8');
if (argv.bom && data.indexOf('\uFEFF') === 0) {
data = data.substring(1);
}
var options = {
knownHelpers: known,
knownHelpersOnly: argv.o
};
if (argv.data) {
options.data = true;
}
// Clean the template name
if (!root) {
template = basename(template);
} else if (template.indexOf(root) === 0) {
template = template.substring(root.length+1);
}
template = template.replace(extension, '');
if (argv.simple) {
output.push(handlebars.precompile(data, options) + '\n');
} else if (argv.partial) {
if(argv.amd && (argv._.length == 1 && !fs.statSync(argv._[0]).isDirectory())) {
output.push('return ');
}
output.push('Handlebars.partials[\'' + template + '\'] = template(' + handlebars.precompile(data, options) + ');\n');
} else {
if(argv.amd && (argv._.length == 1 && !fs.statSync(argv._[0]).isDirectory())) {
output.push('return ');
}
output.push('templates[\'' + template + '\'] = template(' + handlebars.precompile(data, options) + ');\n');
}
}
}
argv._.forEach(function(template) {
processTemplate(template, argv.root);
});
// Output the content
if (!argv.simple) {
if (argv.amd) {
if(argv._.length > 1 || (argv._.length == 1 && fs.statSync(argv._[0]).isDirectory())) {
if(argv.partial){
output.push('return Handlebars.partials;\n');
} else {
output.push('return templates;\n');
}
}
output.push('});');
} else if (!argv.commonjs) {
output.push('})();');
}
}
output = output.join('');
if (argv.min) {
output = uglify.minify(output, {fromString: true}).code;
}
if (argv.output) {
fs.writeFileSync(argv.output, output, 'utf8');
} else {
console.log(output);
}
return require('../lib/precompiler').cli(argv);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "handlebars",
"version": "1.1.0",
"version": "3.0.1",
"main": "handlebars.js",
"dependencies": {}
}
+2 -1
View File
@@ -11,7 +11,8 @@ Gem::Specification.new do |gem|
gem.description = %q{Handlebars.js source code wrapper for (pre)compilation gems.}
gem.summary = %q{Handlebars.js source code wrapper}
gem.homepage = "https://github.com/wycats/handlebars.js/"
gem.version = package["version"]
gem.version = package["version"].sub "-", "."
gem.license = "MIT"
gem.files = [
'handlebars.js',
+1 -1
View File
@@ -2,7 +2,7 @@
<package>
<metadata>
<id>handlebars.js</id>
<version>1.1.0</version>
<version>3.0.1</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>
+268
View File
@@ -0,0 +1,268 @@
# Handlebars Compiler APIs
There are a number of formal APIs that tool implementors may interact with.
## AST
Other tools may interact with the formal AST as defined below. Any JSON structure matching this pattern may be used and passed into the `compile` and `precompile` methods in the same way as the text for a template.
AST structures may be generated either with the `Handlebars.parse` method and then manipulated, via the `Handlebars.AST` objects of the same name, or constructed manually as a generic JavaScript object matching the structure defined below.
```javascript
var ast = Handlebars.parse(myTemplate);
// Modify ast
Handlebars.precompile(ast);
```
### Basic
```java
interface Node {
type: string;
loc: SourceLocation | null;
}
interface SourceLocation {
source: string | null;
start: Position;
end: Position;
}
interface Position {
line: uint >= 1;
column: uint >= 0;
}
```
### Programs
```java
interface Program <: Node {
type: "Program";
body: [ Statement ];
blockParams: [ string ];
}
```
### Statements
```java
interface Statement <: Node { }
interface MustacheStatement <: Statement {
type: "MustacheStatement";
path: PathExpression | Literal;
params: [ Expression ];
hash: Hash;
escaped: boolean;
strip: StripFlags | null;
}
interface BlockStatement <: Statement {
type: "BlockStatement";
path: PathExpression;
params: [ Expression ];
hash: Hash;
program: Program | null;
inverse: Program | null;
openStrip: StripFlags | null;
inverseStrip: StripFlags | null;
closeStrip: StripFlags | null;
}
interface PartialStatement <: Statement {
type: "PartialStatement";
name: PathExpression | SubExpression;
params: [ Expression ];
hash: Hash;
indent: string;
strip: StripFlags | null;
}
```
`name` will be a `SubExpression` when tied to a dynamic partial, i.e. `{{> (foo) }}`, otherwise this is a path or literal whose `original` value is used to lookup the desired partial.
```java
interface ContentStatement <: Statement {
type: "ContentStatement";
value: string;
original: string;
}
interface CommentStatement <: Statement {
type: "CommentStatement";
value: string;
strip: StripFlags | null;
}
```
### Expressions
```java
interface Expression <: Node { }
```
##### SubExpressions
```java
interface SubExpression <: Expression {
type: "SubExpression";
path: PathExpression;
params: [ Expression ];
hash: Hash;
}
```
##### Paths
```java
interface PathExpression <: Expression {
type: "PathExpression";
data: boolean;
depth: uint >= 0;
parts: [ string ];
original: string;
}
```
- `data` is true when the given expression is a `@data` reference.
- `depth` is an integer representation of which context the expression references. `0` represents the current context, `1` would be `../`, etc.
- `parts` is an array of the names in the path. `foo.bar` would be `['foo', 'bar']`. Scope references, `.`, `..`, and `this` should be omitted from this array.
- `original` is the path as entered by the user. Separator and scope references are left untouched.
##### Literals
```java
interface Literal <: Expression { }
interface StringLiteral <: Literal {
type: "StringLiteral";
value: string;
original: string;
}
interface BooleanLiteral <: Literal {
type: "BooleanLiteral";
value: boolean;
original: boolean;
}
interface NumberLiteral <: Literal {
type: "NumberLiteral";
value: number;
original: number;
}
```
### Miscellaneous
```java
interface Hash <: Node {
type: "Hash";
pairs: [ HashPair ];
}
interface HashPair <: Node {
type: "HashPair";
key: string;
value: Expression;
}
interface StripFlags {
open: boolean;
close: boolean;
}
```
`StripFlags` are used to signify whitespace control character that may have been entered on a given statement.
## AST Visitor
`Handlebars.Visitor` is available as a base class for general interaction with AST structures. This will by default traverse the entire tree and individual methods may be overridden to provide specific responses to particular nodes.
Recording all referenced partial names:
```javascript
var Visitor = Handlebars.Visitor;
function ImportScanner() {
this.partials = [];
}
ImportScanner.prototype = new Visitor();
ImportScanner.prototype.PartialStatement = function(partial) {
this.partials.push({request: partial.name.original});
Visitor.prototype.PartialStatement.call(this, partial);
};
var scanner = new ImportScanner();
scanner.accept(ast);
```
The current node's ancestors will be maintained in the `parents` array, with the most recent parent listed first.
The visitor may also be configured to operate in mutation mode by setting the `mutation` field to true. When in this mode, handler methods may return any valid AST node and it will replace the one they are currently operating on. Returning `false` will remove the given value (if valid) and returning `undefined` will leave the node in tact. This return structure only apply to mutation mode and non-mutation mode visitors are free to return whatever values they wish.
Implementors that may need to support mutation mode are encouraged to utilize the `acceptKey`, `acceptRequired` and `acceptArray` helpers which provide the conditional overwrite behavior as well as implement sanity checks where pertinent.
## JavaScript Compiler
The `Handlebars.JavaScriptCompiler` object has a number of methods that may be customized to alter the output of the compiler:
- `nameLookup(parent, name, type)`
Used to generate the code to resolve a give path component.
- `parent` is the existing code in the path resolution
- `name` is the current path component
- `type` is the type of name being evaluated. May be one of `context`, `data`, `helper`, or `partial`.
Note that this does not impact dynamic partials, which implementors need to be aware of. Overriding `VM.resolvePartial` may be required to support dynamic cases.
- `depthedLookup(name)`
Used to generate code that resolves parameters within any context in the stack. Is only used in `compat` mode.
- `compilerInfo()`
Allows for custom compiler flags used in the runtime version checking logic.
- `appendToBuffer(source, location, explicit)`
Allows for code buffer emitting code. Defaults behavior is string concatenation.
- `source` is the source code whose result is to be appending
- `location` is the location of the source in the source map.
- `explicit` is a flag signaling that the emit operation must occur, vs. the lazy evaled options otherwise.
- `initializeBuffer()`
Allows for buffers other than the default string buffer to be used. Generally needs to be paired with a custom `appendToBuffer` implementation.
```javascript
function MyCompiler() {
Handlebars.JavaScriptCompiler.apply(this, arguments);
}
MyCompiler.prototype = Object.create(Handlebars.JavaScriptCompiler);
MyCompiler.nameLookup = function(parent, name, type) {
if (type === 'partial') {
return 'MyPartialList[' + JSON.stringify(name) ']';
} else {
return Handlebars.JavaScriptCompiler.prototype.nameLookup.call(this, parent, name, type);
}
};
var env = Handlebars.create();
env.JavaScriptCompiler = MyCompiler;
env.compile('my template');
```
+18 -2
View File
@@ -1,7 +1,8 @@
/*globals Handlebars: true */
import Handlebars from "./handlebars.runtime";
// Compiler imports
module AST from "./handlebars/compiler/ast";
import AST from "./handlebars/compiler/ast";
import { parser as Parser, parse } from "./handlebars/compiler/base";
import { Compiler, compile, precompile } from "./handlebars/compiler/compiler";
import JavaScriptCompiler from "./handlebars/compiler/javascript-compiler";
@@ -13,7 +14,9 @@ var create = function() {
hb.compile = function(input, options) {
return compile(input, options, hb);
};
hb.precompile = precompile;
hb.precompile = function (input, options) {
return precompile(input, options, hb);
};
hb.AST = AST;
hb.Compiler = Compiler;
@@ -27,4 +30,17 @@ var create = function() {
Handlebars = create();
Handlebars.create = create;
/*jshint -W040 */
/* istanbul ignore next */
var root = typeof global !== 'undefined' ? global : window,
$Handlebars = root.Handlebars;
/* istanbul ignore next */
Handlebars.noConflict = function() {
if (root.Handlebars === Handlebars) {
root.Handlebars = $Handlebars;
}
};
Handlebars['default'] = Handlebars;
export default Handlebars;
+15
View File
@@ -1,3 +1,4 @@
/*globals Handlebars: true */
module base from "./handlebars/base";
// Each of these augment the Handlebars object. No need to setup here.
@@ -15,6 +16,7 @@ var create = function() {
hb.SafeString = SafeString;
hb.Exception = Exception;
hb.Utils = Utils;
hb.escapeExpression = Utils.escapeExpression;
hb.VM = runtime;
hb.template = function(spec) {
@@ -27,4 +29,17 @@ var create = function() {
var Handlebars = create();
Handlebars.create = create;
/*jshint -W040 */
/* istanbul ignore next */
var root = typeof global !== 'undefined' ? global : window,
$Handlebars = root.Handlebars;
/* istanbul ignore next */
Handlebars.noConflict = function() {
if (root.Handlebars === Handlebars) {
root.Handlebars = $Handlebars;
}
};
Handlebars['default'] = Handlebars;
export default Handlebars;
+107 -55
View File
@@ -1,36 +1,23 @@
/*globals Exception, Utils */
module Utils from "./utils";
import Exception from "./exception";
export var VERSION = "1.1.0";
export var COMPILER_REVISION = 4;
export var VERSION = "3.0.1";
export var COMPILER_REVISION = 6;
export var REVISION_CHANGES = {
1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
2: '== 1.0.0-rc.3',
3: '== 1.0.0-rc.4',
4: '>= 1.0.0'
4: '== 1.x.x',
5: '== 2.0.0-alpha.x',
6: '>= 2.0.0-beta.1'
};
var toString = Object.prototype.toString,
var isArray = Utils.isArray,
isFunction = Utils.isFunction,
toString = Utils.toString,
objectType = '[object Object]';
// Sourced from lodash
// https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
var isFunction = function(value) {
return typeof value === 'function';
};
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value === 'function' && toString.call(value) === '[object Function]';
};
}
function isArray(value) {
return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false;
}
export function HandlebarsEnvironment(helpers, partials) {
this.helpers = helpers || {};
this.partials = partials || {};
@@ -44,38 +31,47 @@ HandlebarsEnvironment.prototype = {
logger: logger,
log: log,
registerHelper: function(name, fn, inverse) {
registerHelper: function(name, fn) {
if (toString.call(name) === objectType) {
if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); }
if (fn) { throw new Exception('Arg not supported with multiple helpers'); }
Utils.extend(this.helpers, name);
} else {
if (inverse) { fn.not = inverse; }
this.helpers[name] = fn;
}
},
unregisterHelper: function(name) {
delete this.helpers[name];
},
registerPartial: function(name, str) {
registerPartial: function(name, partial) {
if (toString.call(name) === objectType) {
Utils.extend(this.partials, name);
} else {
this.partials[name] = str;
if (typeof partial === 'undefined') {
throw new Exception('Attempting to register a partial as undefined');
}
this.partials[name] = partial;
}
},
unregisterPartial: function(name) {
delete this.partials[name];
}
};
function registerDefaultHelpers(instance) {
instance.registerHelper('helperMissing', function(arg) {
if(arguments.length === 2) {
instance.registerHelper('helperMissing', function(/* [args, ]options */) {
if(arguments.length === 1) {
// A missing field in a {{foo}} constuct.
return undefined;
} else {
throw new Error("Missing helper: '" + arg + "'");
// Someone is actually trying to call something, blow up.
throw new Exception("Missing helper: '" + arguments[arguments.length-1].name + "'");
}
});
instance.registerHelper('blockHelperMissing', function(context, options) {
var inverse = options.inverse || function() {}, fn = options.fn;
if (isFunction(context)) { context = context.call(this); }
var inverse = options.inverse,
fn = options.fn;
if(context === true) {
return fn(this);
@@ -83,43 +79,85 @@ function registerDefaultHelpers(instance) {
return inverse(this);
} else if (isArray(context)) {
if(context.length > 0) {
if (options.ids) {
options.ids = [options.name];
}
return instance.helpers.each(context, options);
} else {
return inverse(this);
}
} else {
return fn(context);
if (options.data && options.ids) {
var data = createFrame(options.data);
data.contextPath = Utils.appendContextPath(options.data.contextPath, options.name);
options = {data: data};
}
return fn(context, options);
}
});
instance.registerHelper('each', function(context, options) {
if (!options) {
throw new Exception('Must pass iterator to #each');
}
var fn = options.fn, inverse = options.inverse;
var i = 0, ret = "", data;
var contextPath;
if (options.data && options.ids) {
contextPath = Utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
}
if (isFunction(context)) { context = context.call(this); }
if (options.data) {
data = createFrame(options.data);
}
function execIteration(key, i, last) {
if (data) {
data.key = key;
data.index = i;
data.first = i === 0;
data.last = !!last;
if (contextPath) {
data.contextPath = contextPath + key;
}
}
ret = ret + fn(context[key], {
data: data,
blockParams: Utils.blockParams([context[key], key], [contextPath + key, null])
});
}
if(context && typeof context === 'object') {
if (isArray(context)) {
for(var j = context.length; i<j; i++) {
if (data) {
data.index = i;
data.first = (i === 0)
data.last = (i === (context.length-1));
}
ret = ret + fn(context[i], { data: data });
execIteration(i, i, i === context.length-1);
}
} else {
var priorKey;
for(var key in context) {
if(context.hasOwnProperty(key)) {
if(data) { data.key = key; }
ret = ret + fn(context[key], {data: data});
// We're running the iterations one step out of sync so we can detect
// the last iteration without have to scan the object twice and create
// an itermediate keys array.
if (priorKey) {
execIteration(priorKey, i-1);
}
priorKey = key;
i++;
}
}
if (priorKey) {
execIteration(priorKey, i-1, true);
}
}
}
@@ -150,12 +188,28 @@ function registerDefaultHelpers(instance) {
instance.registerHelper('with', function(context, options) {
if (isFunction(context)) { context = context.call(this); }
if (!Utils.isEmpty(context)) return options.fn(context);
var fn = options.fn;
if (!Utils.isEmpty(context)) {
if (options.data && options.ids) {
var data = createFrame(options.data);
data.contextPath = Utils.appendContextPath(options.data.contextPath, options.ids[0]);
options = {data:data};
}
return fn(context, options);
} else {
return options.inverse(this);
}
});
instance.registerHelper('log', function(context, options) {
instance.registerHelper('log', function(message, options) {
var level = options.data && options.data.level != null ? parseInt(options.data.level, 10) : 1;
instance.log(level, context);
instance.log(level, message);
});
instance.registerHelper('lookup', function(obj, field) {
return obj && obj[field];
});
}
@@ -167,23 +221,21 @@ export var logger = {
INFO: 1,
WARN: 2,
ERROR: 3,
level: 3,
level: 1,
// can be overridden in the host environment
log: function(level, obj) {
if (logger.level <= level) {
// Can be overridden in the host environment
log: function(level, message) {
if (typeof console !== 'undefined' && logger.level <= level) {
var method = logger.methodMap[level];
if (typeof console !== 'undefined' && console[method]) {
console[method].call(console, obj);
}
(console[method] || console.log).call(console, message);
}
}
};
export function log(level, obj) { logger.log(level, obj); }
export var log = logger.log;
export var createFrame = function(object) {
var obj = {};
Utils.extend(obj, object);
return obj;
var frame = Utils.extend({}, object);
frame._parent = object;
return frame;
};
+117 -121
View File
@@ -1,145 +1,141 @@
import Exception from "../exception";
var AST = {
Program: function(statements, blockParams, strip, locInfo) {
this.loc = locInfo;
this.type = 'Program';
this.body = statements;
export function ProgramNode(statements, inverseStrip, inverse) {
this.type = "program";
this.statements = statements;
this.strip = {};
this.blockParams = blockParams;
this.strip = strip;
},
if(inverse) {
this.inverse = new ProgramNode(inverse, inverseStrip);
this.strip.right = inverseStrip.left;
} else if (inverseStrip) {
this.strip.left = inverseStrip.right;
}
}
MustacheStatement: function(path, params, hash, escaped, strip, locInfo) {
this.loc = locInfo;
this.type = 'MustacheStatement';
export function MustacheNode(rawParams, hash, open, strip) {
this.type = "mustache";
this.hash = hash;
this.strip = strip;
this.path = path;
this.params = params || [];
this.hash = hash;
this.escaped = escaped;
var escapeFlag = open[3] || open[2];
this.escaped = escapeFlag !== '{' && escapeFlag !== '&';
this.strip = strip;
},
var id = this.id = rawParams[0];
var params = this.params = rawParams.slice(1);
BlockStatement: function(path, params, hash, program, inverse, openStrip, inverseStrip, closeStrip, locInfo) {
this.loc = locInfo;
this.type = 'BlockStatement';
// a mustache is an eligible helper if:
// * its id is simple (a single part, not `this` or `..`)
var eligibleHelper = this.eligibleHelper = id.isSimple;
this.path = path;
this.params = params || [];
this.hash = hash;
this.program = program;
this.inverse = inverse;
// a mustache is definitely a helper if:
// * it is an eligible helper, and
// * it has at least one parameter or hash segment
this.isHelper = eligibleHelper && (params.length || hash);
this.openStrip = openStrip;
this.inverseStrip = inverseStrip;
this.closeStrip = closeStrip;
},
// if a mustache is an eligible helper but not a definite
// helper, it is ambiguous, and will be resolved in a later
// pass or at runtime.
}
PartialStatement: function(name, params, hash, strip, locInfo) {
this.loc = locInfo;
this.type = 'PartialStatement';
export function PartialNode(partialName, context, strip) {
this.type = "partial";
this.partialName = partialName;
this.context = context;
this.strip = strip;
}
this.name = name;
this.params = params || [];
this.hash = hash;
export function BlockNode(mustache, program, inverse, close) {
if(mustache.id.original !== close.path.original) {
throw new Exception(mustache.id.original + " doesn't match " + close.path.original);
}
this.indent = '';
this.strip = strip;
},
this.type = "block";
this.mustache = mustache;
this.program = program;
this.inverse = inverse;
ContentStatement: function(string, locInfo) {
this.loc = locInfo;
this.type = 'ContentStatement';
this.original = this.value = string;
},
this.strip = {
left: mustache.strip.left,
right: close.strip.right
};
CommentStatement: function(comment, strip, locInfo) {
this.loc = locInfo;
this.type = 'CommentStatement';
this.value = comment;
(program || inverse).strip.left = mustache.strip.right;
(inverse || program).strip.right = close.strip.left;
this.strip = strip;
},
if (inverse && !program) {
this.isInverse = true;
}
}
SubExpression: function(path, params, hash, locInfo) {
this.loc = locInfo;
export function ContentNode(string) {
this.type = "content";
this.string = string;
}
this.type = 'SubExpression';
this.path = path;
this.params = params || [];
this.hash = hash;
},
export function HashNode(pairs) {
this.type = "hash";
this.pairs = pairs;
}
PathExpression: function(data, depth, parts, original, locInfo) {
this.loc = locInfo;
this.type = 'PathExpression';
export function IdNode(parts) {
this.type = "ID";
this.data = data;
this.original = original;
this.parts = parts;
this.depth = depth;
},
var original = "",
dig = [],
depth = 0;
StringLiteral: function(string, locInfo) {
this.loc = locInfo;
this.type = 'StringLiteral';
this.original =
this.value = string;
},
for(var i=0,l=parts.length; i<l; i++) {
var part = parts[i].part;
original += (parts[i].separator || '') + part;
NumberLiteral: function(number, locInfo) {
this.loc = locInfo;
this.type = 'NumberLiteral';
this.original =
this.value = Number(number);
},
if (part === ".." || part === "." || part === "this") {
if (dig.length > 0) { throw new Exception("Invalid path: " + original); }
else if (part === "..") { depth++; }
else { this.isScoped = true; }
BooleanLiteral: function(bool, locInfo) {
this.loc = locInfo;
this.type = 'BooleanLiteral';
this.original =
this.value = bool === 'true';
},
Hash: function(pairs, locInfo) {
this.loc = locInfo;
this.type = 'Hash';
this.pairs = pairs;
},
HashPair: function(key, value, locInfo) {
this.loc = locInfo;
this.type = 'HashPair';
this.key = key;
this.value = value;
},
// Public API used to evaluate derived attributes regarding AST nodes
helpers: {
// a mustache is definitely a helper if:
// * it is an eligible helper, and
// * it has at least one parameter or hash segment
// TODO: Make these public utility methods
helperExpression: function(node) {
return !!(node.type === 'SubExpression' || node.params.length || node.hash);
},
scopedId: function(path) {
return (/^\.|this\b/).test(path.original);
},
// an ID is simple if it only has one part, and that part is not
// `..` or `this`.
simpleId: function(path) {
return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
}
else { dig.push(part); }
}
};
this.original = original;
this.parts = dig;
this.string = dig.join('.');
this.depth = depth;
// an ID is simple if it only has one part, and that part is not
// `..` or `this`.
this.isSimple = parts.length === 1 && !this.isScoped && depth === 0;
this.stringModeValue = this.string;
}
export function PartialNameNode(name) {
this.type = "PARTIAL_NAME";
this.name = name.original;
}
export function DataNode(id) {
this.type = "DATA";
this.id = id;
}
export function StringNode(string) {
this.type = "STRING";
this.original =
this.string =
this.stringModeValue = string;
}
export function IntegerNode(integer) {
this.type = "INTEGER";
this.original =
this.integer = integer;
this.stringModeValue = Number(integer);
}
export function BooleanNode(bool) {
this.type = "BOOLEAN";
this.bool = bool;
this.stringModeValue = bool === "true";
}
export function CommentNode(comment) {
this.type = "comment";
this.comment = comment;
}
// Must be exported as an object rather than the root of the module as the jison lexer
// must modify the object to operate properly.
export default AST;
+19 -6
View File
@@ -1,12 +1,25 @@
import parser from "./parser";
module AST from "./ast";
import AST from "./ast";
import WhitespaceControl from "./whitespace-control";
module Helpers from "./helpers";
import { extend } from "../utils";
export { parser };
export function parse(input) {
// Just return if an already-compile AST was passed in.
if(input.constructor === AST.ProgramNode) { return input; }
var yy = {};
extend(yy, Helpers, AST);
parser.yy = AST;
return parser.parse(input);
export function parse(input, options) {
// Just return if an already-compiled AST was passed in.
if (input.type === 'Program') { return input; }
parser.yy = yy;
// Altering the shared object here, but this is ok as parser is a sync operation
yy.locInfo = function(locInfo) {
return new yy.SourceLocation(options && options.srcName, locInfo);
};
var strip = new WhitespaceControl();
return strip.accept(parser.parse(input));
}
+154
View File
@@ -0,0 +1,154 @@
import {isArray} from "../utils";
try {
var SourceMap = require('source-map'),
SourceNode = SourceMap.SourceNode;
} catch (err) {
/* istanbul ignore next: tested but not covered in istanbul due to dist build */
SourceNode = function(line, column, srcFile, chunks) {
this.src = '';
if (chunks) {
this.add(chunks);
}
};
/* istanbul ignore next */
SourceNode.prototype = {
add: function(chunks) {
if (isArray(chunks)) {
chunks = chunks.join('');
}
this.src += chunks;
},
prepend: function(chunks) {
if (isArray(chunks)) {
chunks = chunks.join('');
}
this.src = chunks + this.src;
},
toStringWithSourceMap: function() {
return {code: this.toString()};
},
toString: function() {
return this.src;
}
};
}
function castChunk(chunk, codeGen, loc) {
if (isArray(chunk)) {
var ret = [];
for (var i = 0, len = chunk.length; i < len; i++) {
ret.push(codeGen.wrap(chunk[i], loc));
}
return ret;
} else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
// Handle primitives that the SourceNode will throw up on
return chunk+'';
}
return chunk;
}
function CodeGen(srcFile) {
this.srcFile = srcFile;
this.source = [];
}
CodeGen.prototype = {
prepend: function(source, loc) {
this.source.unshift(this.wrap(source, loc));
},
push: function(source, loc) {
this.source.push(this.wrap(source, loc));
},
merge: function() {
var source = this.empty();
this.each(function(line) {
source.add([' ', line, '\n']);
});
return source;
},
each: function(iter) {
for (var i = 0, len = this.source.length; i < len; i++) {
iter(this.source[i]);
}
},
empty: function(loc) {
loc = loc || this.currentLocation || {start:{}};
return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
},
wrap: function(chunk, loc) {
if (chunk instanceof SourceNode) {
return chunk;
}
loc = loc || this.currentLocation || {start:{}};
chunk = castChunk(chunk, this, loc);
return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
},
functionCall: function(fn, type, params) {
params = this.generateList(params);
return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
},
quotedString: function(str) {
return '"' + (str + '')
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
.replace(/\u2029/g, '\\u2029') + '"';
},
objectLiteral: function(obj) {
var pairs = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var value = castChunk(obj[key], this);
if (value !== 'undefined') {
pairs.push([this.quotedString(key), ':', value]);
}
}
}
var ret = this.generateList(pairs);
ret.prepend('{');
ret.add('}');
return ret;
},
generateList: function(entries, loc) {
var ret = this.empty(loc);
for (var i = 0, len = entries.length; i < len; i++) {
if (i) {
ret.add(',');
}
ret.add(castChunk(entries[i], this, loc));
}
return ret;
},
generateArray: function(entries, loc) {
var ret = this.generateList(entries, loc);
ret.prepend('[');
ret.add(']');
return ret;
}
};
export default CodeGen;
+288 -257
View File
@@ -1,7 +1,9 @@
import Exception from "../exception";
import { parse } from "./base";
import JavaScriptCompiler from "./javascript-compiler";
module AST from "./ast";
import {isArray, indexOf} from "../utils";
import AST from "./ast";
var slice = [].slice;
export function Compiler() {}
@@ -13,30 +15,6 @@ export function Compiler() {}
Compiler.prototype = {
compiler: Compiler,
disassemble: function() {
var opcodes = this.opcodes, opcode, out = [], params, param;
for (var i=0, l=opcodes.length; i<l; i++) {
opcode = opcodes[i];
if (opcode.opcode === 'DECLARE') {
out.push("DECLARE " + opcode.name + "=" + opcode.value);
} else {
params = [];
for (var j=0; j<opcode.args.length; j++) {
param = opcode.args[j];
if (typeof param === "string") {
param = "\"" + param.replace("\n", "\\n") + "\"";
}
params.push(param);
}
out.push(opcode.opcode + " " + params.join(" "));
}
}
return out.join("\n");
},
equals: function(other) {
var len = this.opcodes.length;
if (other.opcodes.length !== len) {
@@ -46,20 +24,14 @@ Compiler.prototype = {
for (var i = 0; i < len; i++) {
var opcode = this.opcodes[i],
otherOpcode = other.opcodes[i];
if (opcode.opcode !== otherOpcode.opcode || opcode.args.length !== otherOpcode.args.length) {
if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
return false;
}
for (var j = 0; j < opcode.args.length; j++) {
if (opcode.args[j] !== otherOpcode.args[j]) {
return false;
}
}
}
// We know that length is the same between the two arrays because they are directly tied
// to the opcode behavior above.
len = this.children.length;
if (other.children.length !== len) {
return false;
}
for (i = 0; i < len; i++) {
if (!this.children[i].equals(other.children[i])) {
return false;
@@ -72,108 +44,95 @@ Compiler.prototype = {
guid: 0,
compile: function(program, options) {
this.sourceNode = [];
this.opcodes = [];
this.children = [];
this.depths = {list: []};
this.options = options;
this.stringParams = options.stringParams;
this.trackIds = options.trackIds;
options.blockParams = options.blockParams || [];
// These changes will propagate to the other compiler components
var knownHelpers = this.options.knownHelpers;
this.options.knownHelpers = {
var knownHelpers = options.knownHelpers;
options.knownHelpers = {
'helperMissing': true,
'blockHelperMissing': true,
'each': true,
'if': true,
'unless': true,
'with': true,
'log': true
'log': true,
'lookup': true
};
if (knownHelpers) {
for (var name in knownHelpers) {
this.options.knownHelpers[name] = knownHelpers[name];
options.knownHelpers[name] = knownHelpers[name];
}
}
return this.accept(program);
},
accept: function(node) {
var strip = node.strip || {},
ret;
if (strip.left) {
this.opcode('strip');
}
ret = this[node.type](node);
if (strip.right) {
this.opcode('strip');
}
return ret;
},
program: function(program) {
var statements = program.statements;
for(var i=0, l=statements.length; i<l; i++) {
this.accept(statements[i]);
}
this.isSimple = l === 1;
this.depths.list = this.depths.list.sort(function(a, b) {
return a - b;
});
return this;
},
compileProgram: function(program) {
var result = new this.compiler().compile(program, this.options);
var guid = this.guid++, depth;
var guid = this.guid++;
this.usePartial = this.usePartial || result.usePartial;
this.children[guid] = result;
for(var i=0, l=result.depths.list.length; i<l; i++) {
depth = result.depths.list[i];
if(depth < 2) { continue; }
else { this.addDepth(depth - 1); }
}
this.useDepths = this.useDepths || result.useDepths;
return guid;
},
block: function(block) {
var mustache = block.mustache,
program = block.program,
accept: function(node) {
this.sourceNode.unshift(node);
var ret = this[node.type](node);
this.sourceNode.shift();
return ret;
},
Program: function(program) {
this.options.blockParams.unshift(program.blockParams);
var body = program.body;
for(var i=0, l=body.length; i<l; i++) {
this.accept(body[i]);
}
this.options.blockParams.shift();
this.isSimple = l === 1;
this.blockParams = program.blockParams ? program.blockParams.length : 0;
return this;
},
BlockStatement: function(block) {
transformLiteralToPath(block);
var program = block.program,
inverse = block.inverse;
if (program) {
program = this.compileProgram(program);
}
program = program && this.compileProgram(program);
inverse = inverse && this.compileProgram(inverse);
if (inverse) {
inverse = this.compileProgram(inverse);
}
var type = this.classifySexpr(block);
var type = this.classifyMustache(mustache);
if (type === "helper") {
this.helperMustache(mustache, program, inverse);
} else if (type === "simple") {
this.simpleMustache(mustache);
if (type === 'helper') {
this.helperSexpr(block, program, inverse);
} else if (type === 'simple') {
this.simpleSexpr(block);
// now that the simple mustache is resolved, we need to
// evaluate it by executing `blockHelperMissing`
this.opcode('pushProgram', program);
this.opcode('pushProgram', inverse);
this.opcode('emptyHash');
this.opcode('blockValue');
this.opcode('blockValue', block.path.original);
} else {
this.ambiguousMustache(mustache, program, inverse);
this.ambiguousSexpr(block, program, inverse);
// now that the simple mustache is resolved, we need to
// evaluate it by executing `blockHelperMissing`
@@ -186,180 +145,181 @@ Compiler.prototype = {
this.opcode('append');
},
hash: function(hash) {
var pairs = hash.pairs, pair, val;
this.opcode('pushHash');
for(var i=0, l=pairs.length; i<l; i++) {
pair = pairs[i];
val = pair[1];
if (this.options.stringParams) {
if(val.depth) {
this.addDepth(val.depth);
}
this.opcode('getContext', val.depth || 0);
this.opcode('pushStringParam', val.stringModeValue, val.type);
} else {
this.accept(val);
}
this.opcode('assignToHash', pair[0]);
}
this.opcode('popHash');
},
partial: function(partial) {
var partialName = partial.partialName;
PartialStatement: function(partial) {
this.usePartial = true;
if(partial.context) {
this.ID(partial.context);
} else {
this.opcode('push', 'depth0');
var params = partial.params;
if (params.length > 1) {
throw new Exception('Unsupported number of partial arguments: ' + params.length, partial);
} else if (!params.length) {
params.push({type: 'PathExpression', parts: [], depth: 0});
}
this.opcode('invokePartial', partialName.name);
var partialName = partial.name.original,
isDynamic = partial.name.type === 'SubExpression';
if (isDynamic) {
this.accept(partial.name);
}
this.setupFullMustacheParams(partial, undefined, undefined, true);
var indent = partial.indent || '';
if (this.options.preventIndent && indent) {
this.opcode('appendContent', indent);
indent = '';
}
this.opcode('invokePartial', isDynamic, partialName, indent);
this.opcode('append');
},
content: function(content) {
this.opcode('appendContent', content.string);
},
MustacheStatement: function(mustache) {
this.SubExpression(mustache);
mustache: function(mustache) {
var options = this.options;
var type = this.classifyMustache(mustache);
if (type === "simple") {
this.simpleMustache(mustache);
} else if (type === "helper") {
this.helperMustache(mustache);
} else {
this.ambiguousMustache(mustache);
}
if(mustache.escaped && !options.noEscape) {
if(mustache.escaped && !this.options.noEscape) {
this.opcode('appendEscaped');
} else {
this.opcode('append');
}
},
ambiguousMustache: function(mustache, program, inverse) {
var id = mustache.id,
name = id.parts[0],
ContentStatement: function(content) {
if (content.value) {
this.opcode('appendContent', content.value);
}
},
CommentStatement: function() {},
SubExpression: function(sexpr) {
transformLiteralToPath(sexpr);
var type = this.classifySexpr(sexpr);
if (type === 'simple') {
this.simpleSexpr(sexpr);
} else if (type === 'helper') {
this.helperSexpr(sexpr);
} else {
this.ambiguousSexpr(sexpr);
}
},
ambiguousSexpr: function(sexpr, program, inverse) {
var path = sexpr.path,
name = path.parts[0],
isBlock = program != null || inverse != null;
this.opcode('getContext', id.depth);
this.opcode('getContext', path.depth);
this.opcode('pushProgram', program);
this.opcode('pushProgram', inverse);
this.accept(path);
this.opcode('invokeAmbiguous', name, isBlock);
},
simpleMustache: function(mustache) {
var id = mustache.id;
if (id.type === 'DATA') {
this.DATA(id);
} else if (id.parts.length) {
this.ID(id);
} else {
// Simplified ID for `this`
this.addDepth(id.depth);
this.opcode('getContext', id.depth);
this.opcode('pushContext');
}
simpleSexpr: function(sexpr) {
this.accept(sexpr.path);
this.opcode('resolvePossibleLambda');
},
helperMustache: function(mustache, program, inverse) {
var params = this.setupFullMustacheParams(mustache, program, inverse),
name = mustache.id.parts[0];
helperSexpr: function(sexpr, program, inverse) {
var params = this.setupFullMustacheParams(sexpr, program, inverse),
path = sexpr.path,
name = path.parts[0];
if (this.options.knownHelpers[name]) {
this.opcode('invokeKnownHelper', params.length, name);
} else if (this.options.knownHelpersOnly) {
throw new Error("You specified knownHelpersOnly, but used the unknown helper " + name);
throw new Exception("You specified knownHelpersOnly, but used the unknown helper " + name, sexpr);
} else {
this.opcode('invokeHelper', params.length, name);
path.falsy = true;
this.accept(path);
this.opcode('invokeHelper', params.length, path.original, AST.helpers.simpleId(path));
}
},
ID: function(id) {
this.addDepth(id.depth);
this.opcode('getContext', id.depth);
PathExpression: function(path) {
this.addDepth(path.depth);
this.opcode('getContext', path.depth);
var name = id.parts[0];
if (!name) {
var name = path.parts[0],
scoped = AST.helpers.scopedId(path),
blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
if (blockParamId) {
this.opcode('lookupBlockParam', blockParamId, path.parts);
} else if (!name) {
// Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
this.opcode('pushContext');
} else if (path.data) {
this.options.data = true;
this.opcode('lookupData', path.depth, path.parts);
} else {
this.opcode('lookupOnContext', id.parts[0]);
}
for(var i=1, l=id.parts.length; i<l; i++) {
this.opcode('lookup', id.parts[i]);
this.opcode('lookupOnContext', path.parts, path.falsy, scoped);
}
},
DATA: function(data) {
this.options.data = true;
if (data.id.isScoped || data.id.depth) {
throw new Exception('Scoped data references are not supported: ' + data.original);
StringLiteral: function(string) {
this.opcode('pushString', string.value);
},
NumberLiteral: function(number) {
this.opcode('pushLiteral', number.value);
},
BooleanLiteral: function(bool) {
this.opcode('pushLiteral', bool.value);
},
Hash: function(hash) {
var pairs = hash.pairs, i, l;
this.opcode('pushHash');
for (i=0, l=pairs.length; i<l; i++) {
this.pushParam(pairs[i].value);
}
this.opcode('lookupData');
var parts = data.id.parts;
for(var i=0, l=parts.length; i<l; i++) {
this.opcode('lookup', parts[i]);
while (i--) {
this.opcode('assignToHash', pairs[i].key);
}
this.opcode('popHash');
},
STRING: function(string) {
this.opcode('pushString', string.string);
},
INTEGER: function(integer) {
this.opcode('pushLiteral', integer.integer);
},
BOOLEAN: function(bool) {
this.opcode('pushLiteral', bool.bool);
},
comment: function() {},
// HELPERS
opcode: function(name) {
this.opcodes.push({ opcode: name, args: [].slice.call(arguments, 1) });
},
declare: function(name, value) {
this.opcodes.push({ opcode: 'DECLARE', name: name, value: value });
this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
},
addDepth: function(depth) {
if(isNaN(depth)) { throw new Error("EWOT"); }
if(depth === 0) { return; }
if(!this.depths[depth]) {
this.depths[depth] = true;
this.depths.list.push(depth);
if (!depth) {
return;
}
this.useDepths = true;
},
classifyMustache: function(mustache) {
var isHelper = mustache.isHelper;
var isEligible = mustache.eligibleHelper;
var options = this.options;
classifySexpr: function(sexpr) {
var isSimple = AST.helpers.simpleId(sexpr.path);
var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
// a mustache is an eligible helper if:
// * its id is simple (a single part, not `this` or `..`)
var isHelper = !isBlockParam && AST.helpers.helperExpression(sexpr);
// if a mustache is an eligible helper but not a definite
// helper, it is ambiguous, and will be resolved in a later
// pass or at runtime.
var isEligible = !isBlockParam && (isHelper || isSimple);
var options = this.options;
// if ambiguous, we can possibly resolve the ambiguity now
// An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
if (isEligible && !isHelper) {
var name = mustache.id.parts[0];
var name = sexpr.path.parts[0];
if (options.knownHelpers[name]) {
isHelper = true;
@@ -368,63 +328,91 @@ Compiler.prototype = {
}
}
if (isHelper) { return "helper"; }
else if (isEligible) { return "ambiguous"; }
else { return "simple"; }
if (isHelper) { return 'helper'; }
else if (isEligible) { return 'ambiguous'; }
else { return 'simple'; }
},
pushParams: function(params) {
var i = params.length, param;
for(var i=0, l=params.length; i<l; i++) {
this.pushParam(params[i]);
}
},
while(i--) {
param = params[i];
pushParam: function(val) {
var value = val.value != null ? val.value : val.original || '';
if(this.options.stringParams) {
if(param.depth) {
this.addDepth(param.depth);
}
this.opcode('getContext', param.depth || 0);
this.opcode('pushStringParam', param.stringModeValue, param.type);
} else {
this[param.type](param);
if (this.stringParams) {
if (value.replace) {
value = value
.replace(/^(\.?\.\/)*/g, '')
.replace(/\//g, '.');
}
}
},
setupMustacheParams: function(mustache) {
var params = mustache.params;
this.pushParams(params);
if(val.depth) {
this.addDepth(val.depth);
}
this.opcode('getContext', val.depth || 0);
this.opcode('pushStringParam', value, val.type);
if(mustache.hash) {
this.hash(mustache.hash);
if (val.type === 'SubExpression') {
// SubExpressions get evaluated and passed in
// in string params mode.
this.accept(val);
}
} else {
this.opcode('emptyHash');
}
if (this.trackIds) {
var blockParamIndex;
if (val.parts && !AST.helpers.scopedId(val) && !val.depth) {
blockParamIndex = this.blockParamIndex(val.parts[0]);
}
if (blockParamIndex) {
var blockParamChild = val.parts.slice(1).join('.');
this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
} else {
value = val.original || value;
if (value.replace) {
value = value
.replace(/^\.\//g, '')
.replace(/^\.$/g, '');
}
return params;
this.opcode('pushId', val.type, value);
}
}
this.accept(val);
}
},
// this will replace setupMustacheParams when we're done
setupFullMustacheParams: function(mustache, program, inverse) {
var params = mustache.params;
setupFullMustacheParams: function(sexpr, program, inverse, omitEmpty) {
var params = sexpr.params;
this.pushParams(params);
this.opcode('pushProgram', program);
this.opcode('pushProgram', inverse);
if(mustache.hash) {
this.hash(mustache.hash);
if (sexpr.hash) {
this.accept(sexpr.hash);
} else {
this.opcode('emptyHash');
this.opcode('emptyHash', omitEmpty);
}
return params;
},
blockParamIndex: function(name) {
for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
var blockParams = this.options.blockParams[depth],
param = blockParams && indexOf(blockParams, name);
if (blockParams && param >= 0) {
return [depth, param];
}
}
}
};
export function precompile(input, options) {
if (input == null || (typeof input !== 'string' && input.constructor !== AST.ProgramNode)) {
export function precompile(input, options, env) {
if (input == null || (typeof input !== 'string' && input.type !== 'Program')) {
throw new Exception("You must pass a string or Handlebars AST to Handlebars.precompile. You passed " + input);
}
@@ -432,14 +420,17 @@ export function precompile(input, options) {
if (!('data' in options)) {
options.data = true;
}
if (options.compat) {
options.useDepths = true;
}
var ast = parse(input);
var environment = new Compiler().compile(ast, options);
return new JavaScriptCompiler().compile(environment, options);
var ast = env.parse(input, options);
var environment = new env.Compiler().compile(ast, options);
return new env.JavaScriptCompiler().compile(environment, options);
}
export function compile(input, options, env) {
if (input == null || (typeof input !== 'string' && input.constructor !== AST.ProgramNode)) {
if (input == null || (typeof input !== 'string' && input.type !== 'Program')) {
throw new Exception("You must pass a string or Handlebars AST to Handlebars.compile. You passed " + input);
}
@@ -448,21 +439,61 @@ export function compile(input, options, env) {
if (!('data' in options)) {
options.data = true;
}
if (options.compat) {
options.useDepths = true;
}
var compiled;
function compileInput() {
var ast = parse(input);
var environment = new Compiler().compile(ast, options);
var templateSpec = new JavaScriptCompiler().compile(environment, options, undefined, true);
var ast = env.parse(input, options);
var environment = new env.Compiler().compile(ast, options);
var templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
return env.template(templateSpec);
}
// Template is only compiled on first use and cached after that point.
return function(context, options) {
var ret = function(context, options) {
if (!compiled) {
compiled = compileInput();
}
return compiled.call(this, context, options);
};
ret._setup = function(options) {
if (!compiled) {
compiled = compileInput();
}
return compiled._setup(options);
};
ret._child = function(i, data, blockParams, depths) {
if (!compiled) {
compiled = compileInput();
}
return compiled._child(i, data, blockParams, depths);
};
return ret;
}
function argEquals(a, b) {
if (a === b) {
return true;
}
if (isArray(a) && isArray(b) && a.length === b.length) {
for (var i = 0; i < a.length; i++) {
if (!argEquals(a[i], b[i])) {
return false;
}
}
return true;
}
}
function transformLiteralToPath(sexpr) {
if (!sexpr.path.parts) {
var literal = sexpr.path;
// Casting to string here to make false and 0 literal values play nicely with the rest
// of the system.
sexpr.path = new AST.PathExpression(false, 0, [literal.original+''], literal.original+'', literal.loc);
}
}
+116
View File
@@ -0,0 +1,116 @@
import Exception from "../exception";
export function SourceLocation(source, locInfo) {
this.source = source;
this.start = {
line: locInfo.first_line,
column: locInfo.first_column
};
this.end = {
line: locInfo.last_line,
column: locInfo.last_column
};
}
export function stripFlags(open, close) {
return {
open: open.charAt(2) === '~',
close: close.charAt(close.length-3) === '~'
};
}
export function stripComment(comment) {
return comment.replace(/^\{\{~?\!-?-?/, '')
.replace(/-?-?~?\}\}$/, '');
}
export function preparePath(data, parts, locInfo) {
/*jshint -W040 */
locInfo = this.locInfo(locInfo);
var original = data ? '@' : '',
dig = [],
depth = 0,
depthString = '';
for(var i=0,l=parts.length; i<l; i++) {
var part = parts[i].part;
original += (parts[i].separator || '') + part;
if (part === '..' || part === '.' || part === 'this') {
if (dig.length > 0) {
throw new Exception('Invalid path: ' + original, {loc: locInfo});
} else if (part === '..') {
depth++;
depthString += '../';
}
} else {
dig.push(part);
}
}
return new this.PathExpression(data, depth, dig, original, locInfo);
}
export function prepareMustache(path, params, hash, open, strip, locInfo) {
/*jshint -W040 */
// Must use charAt to support IE pre-10
var escapeFlag = open.charAt(3) || open.charAt(2),
escaped = escapeFlag !== '{' && escapeFlag !== '&';
return new this.MustacheStatement(path, params, hash, escaped, strip, this.locInfo(locInfo));
}
export function prepareRawBlock(openRawBlock, content, close, locInfo) {
/*jshint -W040 */
if (openRawBlock.path.original !== close) {
var errorNode = {loc: openRawBlock.path.loc};
throw new Exception(openRawBlock.path.original + " doesn't match " + close, errorNode);
}
locInfo = this.locInfo(locInfo);
var program = new this.Program([content], null, {}, locInfo);
return new this.BlockStatement(
openRawBlock.path, openRawBlock.params, openRawBlock.hash,
program, undefined,
{}, {}, {},
locInfo);
}
export function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
/*jshint -W040 */
// When we are chaining inverse calls, we will not have a close path
if (close && close.path && openBlock.path.original !== close.path.original) {
var errorNode = {loc: openBlock.path.loc};
throw new Exception(openBlock.path.original + ' doesn\'t match ' + close.path.original, errorNode);
}
program.blockParams = openBlock.blockParams;
var inverse,
inverseStrip;
if (inverseAndProgram) {
if (inverseAndProgram.chain) {
inverseAndProgram.program.body[0].closeStrip = close.strip;
}
inverseStrip = inverseAndProgram.strip;
inverse = inverseAndProgram.program;
}
if (inverted) {
inverted = inverse;
inverse = program;
program = inverted;
}
return new this.BlockStatement(
openBlock.path, openBlock.params, openBlock.hash,
program, inverse,
openBlock.strip, inverseStrip, close && close.strip,
this.locInfo(locInfo));
}
File diff suppressed because it is too large Load Diff
+71 -67
View File
@@ -10,27 +10,33 @@ export function PrintVisitor() {
PrintVisitor.prototype = new Visitor();
PrintVisitor.prototype.pad = function(string, newline) {
PrintVisitor.prototype.pad = function(string) {
var out = "";
for(var i=0,l=this.padding; i<l; i++) {
out = out + " ";
}
out = out + string;
if(newline !== false) { out = out + "\n"; }
out = out + string + "\n";
return out;
};
PrintVisitor.prototype.program = function(program) {
var out = "",
statements = program.statements,
inverse = program.inverse,
PrintVisitor.prototype.Program = function(program) {
var out = '',
body = program.body,
i, l;
for(i=0, l=statements.length; i<l; i++) {
out = out + this.accept(statements[i]);
if (program.blockParams) {
var blockParams = 'BLOCK PARAMS: [';
for(i=0, l=program.blockParams.length; i<l; i++) {
blockParams += ' ' + program.blockParams[i];
}
blockParams += ' ]';
out += this.pad(blockParams);
}
for(i=0, l=body.length; i<l; i++) {
out = out + this.accept(body[i]);
}
this.padding--;
@@ -38,21 +44,25 @@ PrintVisitor.prototype.program = function(program) {
return out;
};
PrintVisitor.prototype.block = function(block) {
PrintVisitor.prototype.MustacheStatement = function(mustache) {
return this.pad('{{ ' + this.SubExpression(mustache) + ' }}');
};
PrintVisitor.prototype.BlockStatement = function(block) {
var out = "";
out = out + this.pad("BLOCK:");
out = out + this.pad('BLOCK:');
this.padding++;
out = out + this.accept(block.mustache);
out = out + this.pad(this.SubExpression(block));
if (block.program) {
out = out + this.pad("PROGRAM:");
out = out + this.pad('PROGRAM:');
this.padding++;
out = out + this.accept(block.program);
this.padding--;
}
if (block.inverse) {
if (block.program) { this.padding++; }
out = out + this.pad("{{^}}");
out = out + this.pad('{{^}}');
this.padding++;
out = out + this.accept(block.inverse);
this.padding--;
@@ -63,8 +73,27 @@ PrintVisitor.prototype.block = function(block) {
return out;
};
PrintVisitor.prototype.mustache = function(mustache) {
var params = mustache.params, paramStrings = [], hash;
PrintVisitor.prototype.PartialStatement = function(partial) {
var content = 'PARTIAL:' + partial.name.original;
if(partial.params[0]) {
content += ' ' + this.accept(partial.params[0]);
}
if (partial.hash) {
content += ' ' + this.accept(partial.hash);
}
return this.pad('{{> ' + content + ' }}');
};
PrintVisitor.prototype.ContentStatement = function(content) {
return this.pad("CONTENT[ '" + content.value + "' ]");
};
PrintVisitor.prototype.CommentStatement = function(comment) {
return this.pad("{{! '" + comment.value + "' }}");
};
PrintVisitor.prototype.SubExpression = function(sexpr) {
var params = sexpr.params, paramStrings = [], hash;
for(var i=0, l=params.length; i<l; i++) {
paramStrings.push(this.accept(params[i]));
@@ -72,64 +101,39 @@ PrintVisitor.prototype.mustache = function(mustache) {
params = "[" + paramStrings.join(", ") + "]";
hash = mustache.hash ? " " + this.accept(mustache.hash) : "";
hash = sexpr.hash ? " " + this.accept(sexpr.hash) : "";
return this.pad("{{ " + this.accept(mustache.id) + " " + params + hash + " }}");
return this.accept(sexpr.path) + " " + params + hash;
};
PrintVisitor.prototype.partial = function(partial) {
var content = this.accept(partial.partialName);
if(partial.context) { content = content + " " + this.accept(partial.context); }
return this.pad("{{> " + content + " }}");
PrintVisitor.prototype.PathExpression = function(id) {
var path = id.parts.join('/');
return (id.data ? '@' : '') + 'PATH:' + path;
};
PrintVisitor.prototype.hash = function(hash) {
PrintVisitor.prototype.StringLiteral = function(string) {
return '"' + string.value + '"';
};
PrintVisitor.prototype.NumberLiteral = function(number) {
return "NUMBER{" + number.value + "}";
};
PrintVisitor.prototype.BooleanLiteral = function(bool) {
return "BOOLEAN{" + bool.value + "}";
};
PrintVisitor.prototype.Hash = function(hash) {
var pairs = hash.pairs;
var joinedPairs = [], left, right;
var joinedPairs = [];
for(var i=0, l=pairs.length; i<l; i++) {
left = pairs[i][0];
right = this.accept(pairs[i][1]);
joinedPairs.push( left + "=" + right );
for (var i=0, l=pairs.length; i<l; i++) {
joinedPairs.push(this.accept(pairs[i]));
}
return "HASH{" + joinedPairs.join(", ") + "}";
return 'HASH{' + joinedPairs.join(', ') + '}';
};
PrintVisitor.prototype.STRING = function(string) {
return '"' + string.string + '"';
PrintVisitor.prototype.HashPair = function(pair) {
return pair.key + '=' + this.accept(pair.value);
};
PrintVisitor.prototype.INTEGER = function(integer) {
return "INTEGER{" + integer.integer + "}";
};
PrintVisitor.prototype.BOOLEAN = function(bool) {
return "BOOLEAN{" + bool.bool + "}";
};
PrintVisitor.prototype.ID = function(id) {
var path = id.parts.join("/");
if(id.parts.length > 1) {
return "PATH:" + path;
} else {
return "ID:" + path;
}
};
PrintVisitor.prototype.PARTIAL_NAME = function(partialName) {
return "PARTIAL:" + partialName.name;
};
PrintVisitor.prototype.DATA = function(data) {
return "@" + this.accept(data.id);
};
PrintVisitor.prototype.content = function(content) {
return this.pad("CONTENT[ '" + content.string + "' ]");
};
PrintVisitor.prototype.comment = function(comment) {
return this.pad("{{! '" + comment.comment + "' }}");
};
+113 -2
View File
@@ -1,10 +1,121 @@
function Visitor() {}
import Exception from "../exception";
import AST from "./ast";
function Visitor() {
this.parents = [];
}
Visitor.prototype = {
constructor: Visitor,
mutating: false,
// Visits a given value. If mutating, will replace the value if necessary.
acceptKey: function(node, name) {
var value = this.accept(node[name]);
if (this.mutating) {
// Hacky sanity check:
if (value && (!value.type || !AST[value.type])) {
throw new Exception('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
}
node[name] = value;
}
},
// Performs an accept operation with added sanity check to ensure
// required keys are not removed.
acceptRequired: function(node, name) {
this.acceptKey(node, name);
if (!node[name]) {
throw new Exception(node.type + ' requires ' + name);
}
},
// Traverses a given array. If mutating, empty respnses will be removed
// for child elements.
acceptArray: function(array) {
for (var i = 0, l = array.length; i < l; i++) {
this.acceptKey(array, i);
if (!array[i]) {
array.splice(i, 1);
i--;
l--;
}
}
},
accept: function(object) {
return this[object.type](object);
if (!object) {
return;
}
if (this.current) {
this.parents.unshift(this.current);
}
this.current = object;
var ret = this[object.type](object);
this.current = this.parents.shift();
if (!this.mutating || ret) {
return ret;
} else if (ret !== false) {
return object;
}
},
Program: function(program) {
this.acceptArray(program.body);
},
MustacheStatement: function(mustache) {
this.acceptRequired(mustache, 'path');
this.acceptArray(mustache.params);
this.acceptKey(mustache, 'hash');
},
BlockStatement: function(block) {
this.acceptRequired(block, 'path');
this.acceptArray(block.params);
this.acceptKey(block, 'hash');
this.acceptKey(block, 'program');
this.acceptKey(block, 'inverse');
},
PartialStatement: function(partial) {
this.acceptRequired(partial, 'name');
this.acceptArray(partial.params);
this.acceptKey(partial, 'hash');
},
ContentStatement: function(/* content */) {},
CommentStatement: function(/* comment */) {},
SubExpression: function(sexpr) {
this.acceptRequired(sexpr, 'path');
this.acceptArray(sexpr.params);
this.acceptKey(sexpr, 'hash');
},
PartialExpression: function(partial) {
this.acceptRequired(partial, 'name');
this.acceptArray(partial.params);
this.acceptKey(partial, 'hash');
},
PathExpression: function(/* path */) {},
StringLiteral: function(/* string */) {},
NumberLiteral: function(/* number */) {},
BooleanLiteral: function(/* bool */) {},
Hash: function(hash) {
this.acceptArray(hash.pairs);
},
HashPair: function(pair) {
this.acceptRequired(pair, 'value');
}
};
@@ -0,0 +1,211 @@
import Visitor from "./visitor";
function WhitespaceControl() {
}
WhitespaceControl.prototype = new Visitor();
WhitespaceControl.prototype.Program = function(program) {
var isRoot = !this.isRootSeen;
this.isRootSeen = true;
var body = program.body;
for (var i = 0, l = body.length; i < l; i++) {
var current = body[i],
strip = this.accept(current);
if (!strip) {
continue;
}
var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
_isNextWhitespace = isNextWhitespace(body, i, isRoot),
openStandalone = strip.openStandalone && _isPrevWhitespace,
closeStandalone = strip.closeStandalone && _isNextWhitespace,
inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
if (strip.close) {
omitRight(body, i, true);
}
if (strip.open) {
omitLeft(body, i, true);
}
if (inlineStandalone) {
omitRight(body, i);
if (omitLeft(body, i)) {
// If we are on a standalone node, save the indent info for partials
if (current.type === 'PartialStatement') {
// Pull out the whitespace from the final line
current.indent = (/([ \t]+$)/).exec(body[i-1].original)[1];
}
}
}
if (openStandalone) {
omitRight((current.program || current.inverse).body);
// Strip out the previous content node if it's whitespace only
omitLeft(body, i);
}
if (closeStandalone) {
// Always strip the next node
omitRight(body, i);
omitLeft((current.inverse || current.program).body);
}
}
return program;
};
WhitespaceControl.prototype.BlockStatement = function(block) {
this.accept(block.program);
this.accept(block.inverse);
// Find the inverse program that is involed with whitespace stripping.
var program = block.program || block.inverse,
inverse = block.program && block.inverse,
firstInverse = inverse,
lastInverse = inverse;
if (inverse && inverse.chained) {
firstInverse = inverse.body[0].program;
// Walk the inverse chain to find the last inverse that is actually in the chain.
while (lastInverse.chained) {
lastInverse = lastInverse.body[lastInverse.body.length-1].program;
}
}
var strip = {
open: block.openStrip.open,
close: block.closeStrip.close,
// Determine the standalone candiacy. Basically flag our content as being possibly standalone
// so our parent can determine if we actually are standalone
openStandalone: isNextWhitespace(program.body),
closeStandalone: isPrevWhitespace((firstInverse || program).body)
};
if (block.openStrip.close) {
omitRight(program.body, null, true);
}
if (inverse) {
var inverseStrip = block.inverseStrip;
if (inverseStrip.open) {
omitLeft(program.body, null, true);
}
if (inverseStrip.close) {
omitRight(firstInverse.body, null, true);
}
if (block.closeStrip.open) {
omitLeft(lastInverse.body, null, true);
}
// Find standalone else statments
if (isPrevWhitespace(program.body)
&& isNextWhitespace(firstInverse.body)) {
omitLeft(program.body);
omitRight(firstInverse.body);
}
} else {
if (block.closeStrip.open) {
omitLeft(program.body, null, true);
}
}
return strip;
};
WhitespaceControl.prototype.MustacheStatement = function(mustache) {
return mustache.strip;
};
WhitespaceControl.prototype.PartialStatement =
WhitespaceControl.prototype.CommentStatement = function(node) {
/* istanbul ignore next */
var strip = node.strip || {};
return {
inlineStandalone: true,
open: strip.open,
close: strip.close
};
};
function isPrevWhitespace(body, i, isRoot) {
if (i === undefined) {
i = body.length;
}
// Nodes that end with newlines are considered whitespace (but are special
// cased for strip operations)
var prev = body[i-1],
sibling = body[i-2];
if (!prev) {
return isRoot;
}
if (prev.type === 'ContentStatement') {
return (sibling || !isRoot ? (/\r?\n\s*?$/) : (/(^|\r?\n)\s*?$/)).test(prev.original);
}
}
function isNextWhitespace(body, i, isRoot) {
if (i === undefined) {
i = -1;
}
var next = body[i+1],
sibling = body[i+2];
if (!next) {
return isRoot;
}
if (next.type === 'ContentStatement') {
return (sibling || !isRoot ? (/^\s*?\r?\n/) : (/^\s*?(\r?\n|$)/)).test(next.original);
}
}
// Marks the node to the right of the position as omitted.
// I.e. {{foo}}' ' will mark the ' ' node as omitted.
//
// If i is undefined, then the first child will be marked as such.
//
// If mulitple is truthy then all whitespace will be stripped out until non-whitespace
// content is met.
function omitRight(body, i, multiple) {
var current = body[i == null ? 0 : i + 1];
if (!current || current.type !== 'ContentStatement' || (!multiple && current.rightStripped)) {
return;
}
var original = current.value;
current.value = current.value.replace(multiple ? (/^\s+/) : (/^[ \t]*\r?\n?/), '');
current.rightStripped = current.value !== original;
}
// Marks the node to the left of the position as omitted.
// I.e. ' '{{foo}} will mark the ' ' node as omitted.
//
// If i is undefined then the last child will be marked as such.
//
// If mulitple is truthy then all whitespace will be stripped out until non-whitespace
// content is met.
function omitLeft(body, i, multiple) {
var current = body[i == null ? body.length - 1 : i - 1];
if (!current || current.type !== 'ContentStatement' || (!multiple && current.leftStripped)) {
return;
}
// We omit the last node if it's whitespace only and not preceeded by a non-content node.
var original = current.value;
current.value = current.value.replace(multiple ? (/\s+$/) : (/[ \t]+$/), '');
current.leftStripped = current.value !== original;
return current.leftStripped;
}
export default WhitespaceControl;
+17 -2
View File
@@ -1,13 +1,28 @@
var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
function Exception(/* message */) {
var tmp = Error.prototype.constructor.apply(this, arguments);
function Exception(message, node) {
var loc = node && node.loc,
line,
column;
if (loc) {
line = loc.start.line;
column = loc.start.column;
message += ' - ' + line + ':' + column;
}
var tmp = Error.prototype.constructor.call(this, message);
// Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
for (var idx = 0; idx < errorProps.length; idx++) {
this[errorProps[idx]] = tmp[errorProps[idx]];
}
if (loc) {
this.lineNumber = line;
this.column = column;
}
}
Exception.prototype = new Error();
+147 -69
View File
@@ -1,9 +1,8 @@
/*global Utils */
module Utils from "./utils";
import Exception from "./exception";
import { COMPILER_REVISION, REVISION_CHANGES } from "./base";
import { COMPILER_REVISION, REVISION_CHANGES, createFrame } from "./base";
function checkRevision(compilerInfo) {
export function checkRevision(compilerInfo) {
var compilerRevision = compilerInfo && compilerInfo[0] || 1,
currentRevision = COMPILER_REVISION;
@@ -11,11 +10,11 @@ function checkRevision(compilerInfo) {
if (compilerRevision < currentRevision) {
var runtimeVersions = REVISION_CHANGES[currentRevision],
compilerVersions = REVISION_CHANGES[compilerRevision];
throw new Error("Template was precompiled with an older version of Handlebars than the current runtime. "+
throw new Exception("Template was precompiled with an older version of Handlebars than the current runtime. "+
"Please update your precompiler to a newer version ("+runtimeVersions+") or downgrade your runtime to an older version ("+compilerVersions+").");
} else {
// Use the embedded version info since the runtime doesn't know about this revision yet
throw new Error("Template was precompiled with a newer version of Handlebars than the current runtime. "+
throw new Exception("Template was precompiled with a newer version of Handlebars than the current runtime. "+
"Please update your runtime to a newer version ("+compilerInfo[1]+").");
}
}
@@ -24,116 +23,195 @@ function checkRevision(compilerInfo) {
// TODO: Remove this line and break up compilePartial
export function template(templateSpec, env) {
/* istanbul ignore next */
if (!env) {
throw new Error("No environment passed to template");
throw new Exception("No environment passed to template");
}
if (!templateSpec || !templateSpec.main) {
throw new Exception('Unknown template object: ' + typeof templateSpec);
}
var invokePartialWrapper;
if (env.compile) {
invokePartialWrapper = function(partial, name, context, helpers, partials, data) {
// TODO : Check this for all inputs and the options handling (partial flag, etc). This feels
// like there should be a common exec path
var result = invokePartial.apply(this, arguments);
if (result) { return result; }
// Note: Using env.VM references rather than local var references throughout this section to allow
// for external users to override these as psuedo-supported APIs.
env.VM.checkRevision(templateSpec.compiler);
var options = { helpers: helpers, partials: partials, data: data };
partials[name] = env.compile(partial, { data: data !== undefined }, env);
return partials[name](context, options);
};
} else {
invokePartialWrapper = function(partial, name /* , context, helpers, partials, data */) {
var result = invokePartial.apply(this, arguments);
if (result) { return result; }
throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
};
}
var invokePartialWrapper = function(partial, context, options) {
if (options.hash) {
context = Utils.extend({}, context, options.hash);
}
partial = env.VM.resolvePartial.call(this, partial, context, options);
var result = env.VM.invokePartial.call(this, partial, context, options);
if (result == null && env.compile) {
options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
result = options.partials[options.name](context, options);
}
if (result != null) {
if (options.indent) {
var lines = result.split('\n');
for (var i = 0, l = lines.length; i < l; i++) {
if (!lines[i] && i + 1 === l) {
break;
}
lines[i] = options.indent + lines[i];
}
result = lines.join('\n');
}
return result;
} else {
throw new Exception("The partial " + options.name + " could not be compiled when running in runtime-only mode");
}
};
// Just add water
var container = {
strict: function(obj, name) {
if (!(name in obj)) {
throw new Exception('"' + name + '" not defined in ' + obj);
}
return obj[name];
},
lookup: function(depths, name) {
var len = depths.length;
for (var i = 0; i < len; i++) {
if (depths[i] && depths[i][name] != null) {
return depths[i][name];
}
}
},
lambda: function(current, context) {
return typeof current === 'function' ? current.call(context) : current;
},
escapeExpression: Utils.escapeExpression,
invokePartial: invokePartialWrapper,
fn: function(i) {
return templateSpec[i];
},
programs: [],
program: function(i, fn, data) {
var programWrapper = this.programs[i];
if(data) {
programWrapper = program(i, fn, data);
program: function(i, data, declaredBlockParams, blockParams, depths) {
var programWrapper = this.programs[i],
fn = this.fn(i);
if (data || depths || blockParams || declaredBlockParams) {
programWrapper = program(this, i, fn, data, declaredBlockParams, blockParams, depths);
} else if (!programWrapper) {
programWrapper = this.programs[i] = program(i, fn);
programWrapper = this.programs[i] = program(this, i, fn);
}
return programWrapper;
},
data: function(data, depth) {
while (data && depth--) {
data = data._parent;
}
return data;
},
merge: function(param, common) {
var ret = param || common;
if (param && common && (param !== common)) {
ret = {};
Utils.extend(ret, common);
Utils.extend(ret, param);
ret = Utils.extend({}, common, param);
}
return ret;
},
programWithDepth: programWithDepth,
noop: noop,
compilerInfo: null
noop: env.VM.noop,
compilerInfo: templateSpec.compiler
};
return function(context, options) {
var ret = function(context, options) {
options = options || {};
var namespace = options.partial ? options : env,
helpers,
partials;
var data = options.data;
if (!options.partial) {
helpers = options.helpers;
partials = options.partials;
ret._setup(options);
if (!options.partial && templateSpec.useData) {
data = initData(context, data);
}
var result = templateSpec.call(
container,
namespace, context,
helpers,
partials,
options.data);
if (!options.partial) {
checkRevision(container.compilerInfo);
var depths,
blockParams = templateSpec.useBlockParams ? [] : undefined;
if (templateSpec.useDepths) {
depths = options.depths ? [context].concat(options.depths) : [context];
}
return result;
return templateSpec.main.call(container, context, container.helpers, container.partials, data, blockParams, depths);
};
ret.isTop = true;
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, data, blockParams, depths) {
if (templateSpec.useBlockParams && !blockParams) {
throw new Exception('must pass block params');
}
if (templateSpec.useDepths && !depths) {
throw new Exception('must pass parent depths');
}
return program(container, i, templateSpec[i], data, 0, blockParams, depths);
};
return ret;
}
export function programWithDepth(i, fn, data /*, $depth */) {
var args = Array.prototype.slice.call(arguments, 3);
export function program(container, i, fn, data, declaredBlockParams, blockParams, depths) {
var prog = function(context, options) {
options = options || {};
return fn.apply(this, [context, options.data || data].concat(args));
return fn.call(container,
context,
container.helpers, container.partials,
options.data || data,
blockParams && [options.blockParams].concat(blockParams),
depths && [context].concat(depths));
};
prog.program = i;
prog.depth = args.length;
prog.depth = depths ? depths.length : 0;
prog.blockParams = declaredBlockParams || 0;
return prog;
}
export function program(i, fn, data) {
var prog = function(context, options) {
options = options || {};
return fn(context, options.data || data);
};
prog.program = i;
prog.depth = 0;
return prog;
export function resolvePartial(partial, context, options) {
if (!partial) {
partial = options.partials[options.name];
} else if (!partial.call && !options.name) {
// This is a dynamic partial that returned a string
options.name = partial;
partial = options.partials[partial];
}
return partial;
}
export function invokePartial(partial, name, context, helpers, partials, data) {
var options = { partial: true, helpers: helpers, partials: partials, data: data };
export function invokePartial(partial, context, options) {
options.partial = true;
if(partial === undefined) {
throw new Exception("The partial " + name + " could not be found");
throw new Exception("The partial " + options.name + " could not be found");
} else if(partial instanceof Function) {
return partial(context, options);
}
}
export function noop() { return ""; }
function initData(context, data) {
if (!data || !('root' in data)) {
data = data ? createFrame(data) : {};
data.root = context;
}
return data;
}
+1 -1
View File
@@ -3,7 +3,7 @@ function SafeString(string) {
this.string = string;
}
SafeString.prototype.toString = function() {
SafeString.prototype.toString = SafeString.prototype.toHTML = function() {
return "" + this.string;
};
+66 -20
View File
@@ -1,7 +1,4 @@
import SafeString from "./safe-string";
var isArray = Array.isArray;
/*jshint -W004 */
var escape = {
"&": "&amp;",
"<": "&lt;",
@@ -15,31 +12,71 @@ var badChars = /[&<>"'`]/g;
var possible = /[&<>"'`]/;
function escapeChar(chr) {
return escape[chr] || "&amp;";
return escape[chr];
}
export function extend(obj, value) {
for(var key in value) {
if(value.hasOwnProperty(key)) {
obj[key] = value[key];
export function extend(obj /* , ...source */) {
for (var i = 1; i < arguments.length; i++) {
for (var key in arguments[i]) {
if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
obj[key] = arguments[i][key];
}
}
}
return obj;
}
export var toString = Object.prototype.toString;
// Sourced from lodash
// https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
var isFunction = function(value) {
return typeof value === 'function';
};
// fallback for older versions of Chrome and Safari
/* istanbul ignore next */
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value === 'function' && toString.call(value) === '[object Function]';
};
}
export var isFunction;
/* istanbul ignore next */
export var isArray = Array.isArray || function(value) {
return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false;
};
// Older IE versions do not directly support indexOf so we must implement our own, sadly.
export function indexOf(array, value) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i] === value) {
return i;
}
}
return -1;
}
export function escapeExpression(string) {
// don't escape SafeStrings, since they're already safe
if (string instanceof SafeString) {
return string.toString();
} else if (!string && string !== 0) {
return "";
if (typeof string !== 'string') {
// don't escape SafeStrings, since they're already safe
if (string && string.toHTML) {
return string.toHTML();
} else if (string == null) {
return '';
} else if (!string) {
return string + '';
}
// Force a string conversion as this will be done by the append regardless and
// the regex test will do this transparently behind the scenes, causing issues if
// an object's to string has escaped characters in it.
string = '' + string;
}
// Force a string conversion as this will be done by the append regardless and
// the regex test will do this transparently behind the scenes, causing issues if
// an object's to string has escaped characters in it.
string = "" + string;
if(!possible.test(string)) { return string; }
if (!possible.test(string)) { return string; }
return string.replace(badChars, escapeChar);
}
@@ -52,3 +89,12 @@ export function isEmpty(value) {
return false;
}
}
export function blockParams(params, ids) {
params.path = ids;
return params;
}
export function appendContextPath(contextPath, id) {
return (contextPath ? contextPath + '.' : '') + id;
}
+3 -2
View File
@@ -3,9 +3,9 @@
// var local = handlebars.create();
var handlebars = require('../dist/cjs/handlebars').default;
var handlebars = require('../dist/cjs/handlebars')["default"];
handlebars.Visitor = require('../dist/cjs/handlebars/compiler/visitor').default;
handlebars.Visitor = require('../dist/cjs/handlebars/compiler/visitor')["default"];
var printer = require('../dist/cjs/handlebars/compiler/printer');
handlebars.PrintVisitor = printer.PrintVisitor;
@@ -14,6 +14,7 @@ handlebars.print = printer.print;
module.exports = handlebars;
// Publish a Node.js require() handler for .handlebars and .hbs files
/* istanbul ignore else */
if (typeof require !== 'undefined' && require.extensions) {
var extension = function(module, filename) {
var fs = require("fs");
+180
View File
@@ -0,0 +1,180 @@
var fs = require('fs'),
Handlebars = require('./index'),
basename = require('path').basename,
SourceMap = require('source-map'),
SourceMapConsumer = SourceMap.SourceMapConsumer,
SourceNode = SourceMap.SourceNode,
uglify = require('uglify-js');
module.exports.cli = function(opts) {
if (opts.version) {
console.log(Handlebars.VERSION);
return;
}
if (!opts.templates.length) {
throw new Handlebars.Exception('Must define at least one template or directory.');
}
opts.templates.forEach(function(template) {
try {
fs.statSync(template);
} catch (err) {
throw new Handlebars.Exception('Unable to open template file "' + template + '"');
}
});
if (opts.simple && opts.min) {
throw new Handlebars.Exception('Unable to minimize simple output');
}
if (opts.simple && (opts.templates.length !== 1 || fs.statSync(opts.templates[0]).isDirectory())) {
throw new Handlebars.Exception('Unable to output multiple templates in simple mode');
}
// Convert the known list into a hash
var known = {};
if (opts.known && !Array.isArray(opts.known)) {
opts.known = [opts.known];
}
if (opts.known) {
for (var i = 0, len = opts.known.length; i < len; i++) {
known[opts.known[i]] = true;
}
}
// Build file extension pattern
var extension = opts.extension.replace(/[\\^$*+?.():=!|{}\-\[\]]/g, function(arg) { return '\\' + arg; });
extension = new RegExp('\\.' + extension + '$');
var output = new SourceNode();
if (!opts.simple) {
if (opts.amd) {
output.add('define([\'' + opts.handlebarPath + 'handlebars.runtime\'], function(Handlebars) {\n Handlebars = Handlebars["default"];');
} else if (opts.commonjs) {
output.add('var Handlebars = require("' + opts.commonjs + '");');
} else {
output.add('(function() {\n');
}
output.add(' var template = Handlebars.template, templates = ');
if (opts.namespace) {
output.add(opts.namespace);
output.add(' = ');
output.add(opts.namespace);
output.add(' || ');
}
output.add('{};\n');
}
function processTemplate(template, root) {
var path = template,
stat = fs.statSync(path);
if (stat.isDirectory()) {
fs.readdirSync(template).map(function(file) {
var path = template + '/' + file;
if (extension.test(path) || fs.statSync(path).isDirectory()) {
processTemplate(path, root || template);
}
});
} else {
var data = fs.readFileSync(path, 'utf8');
if (opts.bom && data.indexOf('\uFEFF') === 0) {
data = data.substring(1);
}
var options = {
knownHelpers: known,
knownHelpersOnly: opts.o
};
if (opts.map) {
options.srcName = path;
}
if (opts.data) {
options.data = true;
}
// Clean the template name
if (!root) {
template = basename(template);
} else if (template.indexOf(root) === 0) {
template = template.substring(root.length+1);
}
template = template.replace(extension, '');
var precompiled = Handlebars.precompile(data, options);
// If we are generating a source map, we have to reconstruct the SourceNode object
if (opts.map) {
var consumer = new SourceMapConsumer(precompiled.map);
precompiled = SourceNode.fromStringWithSourceMap(precompiled.code, consumer);
}
if (opts.simple) {
output.add([precompiled, '\n']);
} else if (opts.partial) {
if(opts.amd && (opts.templates.length == 1 && !fs.statSync(opts.templates[0]).isDirectory())) {
output.add('return ');
}
output.add(['Handlebars.partials[\'', template, '\'] = template(', precompiled, ');\n']);
} else {
if(opts.amd && (opts.templates.length == 1 && !fs.statSync(opts.templates[0]).isDirectory())) {
output.add('return ');
}
output.add(['templates[\'', template, '\'] = template(', precompiled, ');\n']);
}
}
}
opts.templates.forEach(function(template) {
processTemplate(template, opts.root);
});
// Output the content
if (!opts.simple) {
if (opts.amd) {
if(opts.templates.length > 1 || (opts.templates.length == 1 && fs.statSync(opts.templates[0]).isDirectory())) {
if(opts.partial){
output.add('return Handlebars.partials;\n');
} else {
output.add('return templates;\n');
}
}
output.add('});');
} else if (!opts.commonjs) {
output.add('})();');
}
}
if (opts.map) {
output.add('\n//# sourceMappingURL=' + opts.map + '\n');
}
output = output.toStringWithSourceMap();
output.map = output.map + '';
if (opts.min) {
output = uglify.minify(output.code, {
fromString: true,
outSourceMap: opts.map,
inSourceMap: JSON.parse(output.map)
});
if (opts.map) {
output.code += '\n//# sourceMappingURL=' + opts.map + '\n';
}
}
if (opts.map) {
fs.writeFileSync(opts.map, output.map, 'utf8');
}
output = output.code;
if (opts.output) {
fs.writeFileSync(opts.output, output, 'utf8');
} else {
console.log(output);
}
};
+31 -17
View File
@@ -1,7 +1,7 @@
{
"name": "handlebars",
"barename": "handlebars",
"version": "1.1.0",
"version": "3.0.1",
"description": "Handlebars provides the power necessary to let you build semantic templates effectively with no frustration",
"homepage": "http://www.handlebarsjs.com/",
"keywords": [
@@ -15,38 +15,43 @@
"url": "https://github.com/wycats/handlebars.js.git"
},
"author": "Yehuda Katz",
"license": "BSD",
"license": "MIT",
"readmeFilename": "README.md",
"engines": {
"node": ">=0.4.7"
},
"dependencies": {
"optimist": "~0.3"
"optimist": "^0.6.1",
"source-map": "^0.1.40"
},
"optionalDependencies": {
"uglify-js": "~2.3"
},
"devDependencies": {
"async": "~0.2.9",
"async": "^0.9.0",
"aws-sdk": "~1.5.0",
"benchmark": "~1.0",
"dustjs-linkedin": "~2.0.2",
"dustjs-linkedin": "^2.0.2",
"eco": "~1.1.0-rc-3",
"es6-module-packager": "^2.0.0",
"grunt": "~0.4.1",
"grunt-contrib-clean": "~0.4.1",
"grunt-contrib-copy": "~0.4.1",
"grunt-contrib-jshint": "~0.6.3",
"grunt-contrib-requirejs": "~0.4.1",
"grunt-contrib-uglify": "~0.2.2",
"grunt-es6-module-transpiler": "joefiorini/grunt-es6-module-transpiler",
"es6-module-packager": "*",
"grunt-cli": "~0.1.10",
"grunt-contrib-clean": "0.x",
"grunt-contrib-concat": "0.x",
"grunt-contrib-connect": "0.x",
"grunt-contrib-copy": "0.x",
"grunt-contrib-jshint": "0.x",
"grunt-contrib-requirejs": "0.x",
"grunt-contrib-uglify": "0.x",
"grunt-contrib-watch": "0.x",
"grunt-saucelabs": "8.x",
"istanbul": "^0.3.0",
"jison": "~0.3.0",
"keen.io": "0.0.3",
"mocha": "*",
"mustache": "~0.7.2",
"semver": "~2.1.0",
"should": "~1.2.2",
"underscore": "~1.5.1"
"mocha": "~1.20.0",
"mustache": "0.x",
"semver": "^4.0.0",
"underscore": "^1.5.1"
},
"main": "lib/index.js",
"bin": {
@@ -54,5 +59,14 @@
},
"scripts": {
"test": "grunt"
},
"jspm": {
"main": "handlebars",
"directories": {
"lib": "dist/amd"
},
"buildConfig": {
"minify": true
}
}
}
+236 -3
View File
@@ -2,7 +2,240 @@
## Development
[Commits](https://github.com/wycats/handlebars.js/compare/v1.1.0...master)
[Commits](https://github.com/wycats/handlebars.js/compare/v3.0.1...master)
## v3.0.1 - March 24th, 2015
- [#984](https://github.com/wycats/handlebars.js/pull/984) - Adding documentation for passing arguments into partials ([@johneke](https://api.github.com/users/johneke))
- [#973](https://github.com/wycats/handlebars.js/issues/973) - version 3 is slower than version 2 ([@elover](https://api.github.com/users/elover))
- [#966](https://github.com/wycats/handlebars.js/issues/966) - "handlebars --version" does not work with v3.0.0 ([@abloomston](https://api.github.com/users/abloomston))
- [#964](https://github.com/wycats/handlebars.js/pull/964) - default is a reserved word ([@grassick](https://api.github.com/users/grassick))
- [#962](https://github.com/wycats/handlebars.js/pull/962) - Add dashbars' link on README. ([@pismute](https://api.github.com/users/pismute))
[Commits](https://github.com/wycats/handlebars.js/compare/v3.0.0...v3.0.1)
## v3.0.0 - February 10th, 2015
- [#941](https://github.com/wycats/handlebars.js/pull/941) - Add support for dynamic partial names ([@kpdecker](https://api.github.com/users/kpdecker))
- [#940](https://github.com/wycats/handlebars.js/pull/940) - Add missing reserved words so compiler knows to use array syntax: ([@mattflaschen](https://api.github.com/users/mattflaschen))
- [#938](https://github.com/wycats/handlebars.js/pull/938) - Fix example using #with helper ([@diwo](https://api.github.com/users/diwo))
- [#930](https://github.com/wycats/handlebars.js/pull/930) - Add parent tracking and mutation to AST visitors ([@kpdecker](https://api.github.com/users/kpdecker))
- [#926](https://github.com/wycats/handlebars.js/issues/926) - Depthed lookups fail when program duplicator runs ([@kpdecker](https://api.github.com/users/kpdecker))
- [#918](https://github.com/wycats/handlebars.js/pull/918) - Add instructions for 'spec/mustache' to CONTRIBUTING.md, fix a few typos ([@oneeman](https://api.github.com/users/oneeman))
- [#915](https://github.com/wycats/handlebars.js/pull/915) - Ast update ([@kpdecker](https://api.github.com/users/kpdecker))
- [#910](https://github.com/wycats/handlebars.js/issues/910) - Different behavior of {{@last}} when {{#each}} in {{#each}} ([@zordius](https://api.github.com/users/zordius))
- [#907](https://github.com/wycats/handlebars.js/issues/907) - Implement named helper variable references ([@kpdecker](https://api.github.com/users/kpdecker))
- [#906](https://github.com/wycats/handlebars.js/pull/906) - Add parser support for block params ([@mmun](https://api.github.com/users/mmun))
- [#903](https://github.com/wycats/handlebars.js/issues/903) - Only provide aliases for multiple use calls ([@kpdecker](https://api.github.com/users/kpdecker))
- [#902](https://github.com/wycats/handlebars.js/pull/902) - Generate Source Maps ([@kpdecker](https://api.github.com/users/kpdecker))
- [#901](https://github.com/wycats/handlebars.js/issues/901) - Still escapes with noEscape enabled on isolated Handlebars environment ([@zedknight](https://api.github.com/users/zedknight))
- [#896](https://github.com/wycats/handlebars.js/pull/896) - Simplify BlockNode by removing intermediate MustacheNode ([@mmun](https://api.github.com/users/mmun))
- [#892](https://github.com/wycats/handlebars.js/pull/892) - Implement parser for else chaining of helpers ([@kpdecker](https://api.github.com/users/kpdecker))
- [#889](https://github.com/wycats/handlebars.js/issues/889) - Consider extensible parser API ([@kpdecker](https://api.github.com/users/kpdecker))
- [#887](https://github.com/wycats/handlebars.js/issues/887) - Handlebars.noConflict() option? ([@bradvogel](https://api.github.com/users/bradvogel))
- [#886](https://github.com/wycats/handlebars.js/issues/886) - Add SafeString to context (or use duck-typing) ([@dominicbarnes](https://api.github.com/users/dominicbarnes))
- [#870](https://github.com/wycats/handlebars.js/pull/870) - Registering undefined partial throws exception. ([@max-b](https://api.github.com/users/max-b))
- [#866](https://github.com/wycats/handlebars.js/issues/866) - comments don't respect whitespace control ([@75lb](https://api.github.com/users/75lb))
- [#863](https://github.com/wycats/handlebars.js/pull/863) - + jsDelivr CDN info ([@tomByrer](https://api.github.com/users/tomByrer))
- [#858](https://github.com/wycats/handlebars.js/issues/858) - Disable new default auto-indent at included partials ([@majodev](https://api.github.com/users/majodev))
- [#856](https://github.com/wycats/handlebars.js/pull/856) - jspm compatibility ([@MajorBreakfast](https://api.github.com/users/MajorBreakfast))
- [#805](https://github.com/wycats/handlebars.js/issues/805) - Request: "strict" lookups ([@nzakas](https://api.github.com/users/nzakas))
- Export the default object for handlebars/runtime - 5594416
- Lookup partials when undefined - 617dd57
Compatibility notes:
- Runtime breaking changes. Must match 3.x runtime and precompiler.
- The AST has been upgraded to a public API.
- There are a number of changes to this, but the format is now documented in docs/compiler-api.md
- The Visitor API has been expanded to support mutation and provide a base implementation
- The `JavaScriptCompiler` APIs have been formalized and documented. As part of the sourcemap handling these should be updated to return arrays for concatenation.
- `JavaScriptCompiler.namespace` has been removed as it was unused.
- `SafeString` is now duck typed on `toHTML`
New Features:
- noConflict
- Source Maps
- Block Params
- Strict Mode
- @last and other each changes
- Chained else blocks
- @data methods can now have helper parameters passed to them
- Dynamic partials
[Commits](https://github.com/wycats/handlebars.js/compare/v2.0.0...v3.0.0)
## v2.0.0 - September 1st, 2014
- Update jsfiddle to 2.0.0-beta.1 - 0670f65
- Add contrib note regarding handlebarsjs.com docs - 4d17e3c
- Play nice with gemspec version numbers - 64d5481
[Commits](https://github.com/wycats/handlebars.js/compare/v2.0.0-beta.1...v2.0.0)
## v2.0.0-beta.1 - August 26th, 2014
- [#787](https://github.com/wycats/handlebars.js/pull/787) - Remove whitespace surrounding standalone statements ([@kpdecker](https://api.github.com/users/kpdecker))
- [#827](https://github.com/wycats/handlebars.js/issues/827) - Render false literal as “false” ([@scoot557](https://api.github.com/users/scoot557))
- [#767](https://github.com/wycats/handlebars.js/issues/767) - Subexpressions bug with hash and context ([@evensoul](https://api.github.com/users/evensoul))
- Changes to 0/undefined handling
- [#731](https://github.com/wycats/handlebars.js/pull/731) - Strange behavior for {{#foo}} {{bar}} {{/foo}} when foo is 0 ([@kpdecker](https://api.github.com/users/kpdecker))
- [#820](https://github.com/wycats/handlebars.js/issues/820) - strange behavior for {{foo.bar}} when foo is 0 or null or false ([@zordius](https://api.github.com/users/zordius))
- [#837](https://github.com/wycats/handlebars.js/issues/837) - Strange input for custom helper ( foo.bar == false when foo is undefined ) ([@zordius](https://api.github.com/users/zordius))
- [#819](https://github.com/wycats/handlebars.js/pull/819) - Implement recursive field lookup ([@kpdecker](https://api.github.com/users/kpdecker))
- [#764](https://github.com/wycats/handlebars.js/issues/764) - This reference not working for helpers ([@kpdecker](https://api.github.com/users/kpdecker))
- [#773](https://github.com/wycats/handlebars.js/issues/773) - Implicit parameters in {{#each}} introduces a peculiarity in helpers calling convention ([@Bertrand](https://api.github.com/users/Bertrand))
- [#783](https://github.com/wycats/handlebars.js/issues/783) - helperMissing and consistency for different expression types ([@ErisDS](https://api.github.com/users/ErisDS))
- [#795](https://github.com/wycats/handlebars.js/pull/795) - Turn the precompile script into a wrapper around a module. ([@jwietelmann](https://api.github.com/users/jwietelmann))
- [#823](https://github.com/wycats/handlebars.js/pull/823) - Support inverse sections on the with helper ([@dan-manges](https://api.github.com/users/dan-manges))
- [#834](https://github.com/wycats/handlebars.js/pull/834) - Refactor blocks, programs and inverses ([@mmun](https://api.github.com/users/mmun))
- [#852](https://github.com/wycats/handlebars.js/issues/852) - {{foo~}} space control behavior is different from older version ([@zordius](https://api.github.com/users/zordius))
- [#835](https://github.com/wycats/handlebars.js/issues/835) - Templates overwritten if file is loaded twice
- Expose escapeExpression on the root object - 980c38c
- Remove nested function eval in blockHelperMissing - 6f22ec1
- Fix compiler program de-duping - 9e3f824
Compatibility notes:
- The default build now outputs a generic UMD wrapper. This should be transparent change but may cause issues in some environments.
- Runtime compatibility breaks in both directions. Ensure that both compiler and client are upgraded to 2.0.0-beta.1 or higher at the same time.
- `programWithDepth` has been removed an instead an array of context values is passed to fields needing depth lookups.
- `false` values are now printed to output rather than silently dropped
- Lines containing only block statements and whitespace are now removed. This matches the Mustache spec but may cause issues with code that expects whitespace to exist but would not otherwise.
- Partials that are standalone will now indent their rendered content
- `AST.ProgramNode`'s signature has changed.
- Numerious methods/features removed from psuedo-API classes
- `JavaScriptCompiler.register`
- `JavaScriptCompiler.replaceStack` no longer supports non-inline replace
- `Compiler.disassemble`
- `DECLARE` opcode
- `strip` opcode
- `lookup` opcode
- Content nodes may have their `string` values mutated over time. `original` field provides the unmodified value.
- Removed unused `Handlebars.registerHelper` `inverse` parameter
- `each` helper requires iterator parameter
[Commits](https://github.com/wycats/handlebars.js/compare/v2.0.0-alpha.4...v2.0.0-beta.1)
## 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))
- [#392](https://github.com/wycats/handlebars.js/pull/392) - Access to root context in partials and helpers ([@kpdecker](https://api.github.com/users/kpdecker))
- [#472](https://github.com/wycats/handlebars.js/issues/472) - Helpers cannot have decimal parameters ([@kayleg](https://api.github.com/users/kayleg))
- [#569](https://github.com/wycats/handlebars.js/pull/569) - Unable to lookup array values using @index ([@kpdecker](https://api.github.com/users/kpdecker))
- [#491](https://github.com/wycats/handlebars.js/pull/491) - For nested helpers: get the @ variables of the outer helper from the inner one ([@kpdecker](https://api.github.com/users/kpdecker))
- [#669](https://github.com/wycats/handlebars.js/issues/669) - Ability to unregister a helper ([@dbachrach](https://api.github.com/users/dbachrach))
- [#730](https://github.com/wycats/handlebars.js/pull/730) - Raw block helpers ([@kpdecker](https://api.github.com/users/kpdecker))
- [#634](https://github.com/wycats/handlebars.js/pull/634) - It would be great to have the helper name passed to `blockHelperMissing` ([@kpdecker](https://api.github.com/users/kpdecker))
- [#729](https://github.com/wycats/handlebars.js/pull/729) - Convert template spec to object literal ([@kpdecker](https://api.github.com/users/kpdecker))
- [#658](https://github.com/wycats/handlebars.js/issues/658) - Depthed helpers do not work after an upgrade from 1.0.0 ([@xibxor](https://api.github.com/users/xibxor))
- [#671](https://github.com/wycats/handlebars.js/issues/671) - Crashes on no-parameter {{#each}} ([@stepancheg](https://api.github.com/users/stepancheg))
- [#689](https://github.com/wycats/handlebars.js/issues/689) - broken template precompilation ([@AAS](https://api.github.com/users/AAS))
- [#698](https://github.com/wycats/handlebars.js/pull/698) - Fix parser generation under windows ([@osiris43](https://api.github.com/users/osiris43))
- [#699](https://github.com/wycats/handlebars.js/issues/699) - @DATA not compiles to invalid JS in stringParams mode ([@kpdecker](https://api.github.com/users/kpdecker))
- [#705](https://github.com/wycats/handlebars.js/issues/705) - 1.3.0 can not be wrapped in an IIFE ([@craigteegarden](https://api.github.com/users/craigteegarden))
- [#706](https://github.com/wycats/handlebars.js/pull/706) - README: Use with helper instead of relying on blockHelperMissing ([@scottgonzalez](https://api.github.com/users/scottgonzalez))
- [#700](https://github.com/wycats/handlebars.js/pull/700) - Remove redundant conditions ([@blakeembrey](https://api.github.com/users/blakeembrey))
- [#704](https://github.com/wycats/handlebars.js/pull/704) - JavaScript Compiler Cleanup ([@blakeembrey](https://api.github.com/users/blakeembrey))
Compatibility notes:
- `helperMissing` helper no longer has the indexed name argument. Helper name is now available via `options.name`.
- Precompiler output has changed, which breaks compatibility with prior versions of the runtime and precompiled output.
- `JavaScriptCompiler.compilerInfo` now returns generic objects rather than javascript source.
- AST changes
- INTEGER -> NUMBER
- Additional PartialNode hash parameter
- New RawBlockNode type
- Data frames now have a `_parent` field. This is internal but is enumerable for performance/compatability reasons.
[Commits](https://github.com/wycats/handlebars.js/compare/v1.3.0...v2.0.0-alpha.1)
## v1.3.0 - January 1st, 2014
- [#690](https://github.com/wycats/handlebars.js/pull/690) - Added support for subexpressions ([@machty](https://api.github.com/users/machty))
- [#696](https://github.com/wycats/handlebars.js/pull/696) - Fix for reserved keyword "default" ([@nateirwin](https://api.github.com/users/nateirwin))
- [#692](https://github.com/wycats/handlebars.js/pull/692) - add line numbers to nodes when parsing ([@fivetanley](https://api.github.com/users/fivetanley))
- [#695](https://github.com/wycats/handlebars.js/pull/695) - Pull options out from param setup to allow easier extension ([@blakeembrey](https://api.github.com/users/blakeembrey))
- [#694](https://github.com/wycats/handlebars.js/pull/694) - Make the environment reusable ([@blakeembrey](https://api.github.com/users/blakeembrey))
- [#636](https://github.com/wycats/handlebars.js/issues/636) - Print line and column of errors ([@sgronblo](https://api.github.com/users/sgronblo))
- Use literal for data lookup - c1a93d3
- Add stack handling sanity checks - cd885bf
- Fix stack id "leak" on replaceStack - ddfe457
- Fix incorrect stack pop when replacing literals - f4d337d
[Commits](https://github.com/wycats/handlebars.js/compare/v1.2.1...v1.3.0)
## v1.2.1 - December 26th, 2013
- [#684](https://github.com/wycats/handlebars.js/pull/684) - Allow any number of trailing characters for valid JavaScript variable ([@blakeembrey](https://api.github.com/users/blakeembrey))
- [#686](https://github.com/wycats/handlebars.js/pull/686) - Falsy AMD module names in version 1.2.0 ([@kpdecker](https://api.github.com/users/kpdecker))
[Commits](https://github.com/wycats/handlebars.js/compare/v1.2.0...v1.2.1)
## v1.2.0 - December 23rd, 2013
- [#675](https://github.com/wycats/handlebars.js/issues/675) - Cannot compile empty template for partial ([@erwinw](https://api.github.com/users/erwinw))
- [#677](https://github.com/wycats/handlebars.js/issues/677) - Triple brace statements fail under IE ([@hamzaCM](https://api.github.com/users/hamzaCM))
- [#655](https://github.com/wycats/handlebars.js/issues/655) - Loading Handlebars using bower ([@niki4810](https://api.github.com/users/niki4810))
- [#657](https://github.com/wycats/handlebars.js/pull/657) - Fixes issue where cli compiles non handlebars templates ([@chrishoage](https://api.github.com/users/chrishoage))
- [#681](https://github.com/wycats/handlebars.js/pull/681) - Adds in-browser testing and Saucelabs CI ([@kpdecker](https://api.github.com/users/kpdecker))
- [#661](https://github.com/wycats/handlebars.js/pull/661) - Add @first and @index to #each object iteration ([@cgp](https://api.github.com/users/cgp))
- [#650](https://github.com/wycats/handlebars.js/pull/650) - Handlebars is MIT-licensed ([@thomasboyt](https://api.github.com/users/thomasboyt))
- [#641](https://github.com/wycats/handlebars.js/pull/641) - Document ember testing process ([@kpdecker](https://api.github.com/users/kpdecker))
- [#662](https://github.com/wycats/handlebars.js/issues/662) - handlebars-source 1.1.2 is missing from RubyGems.
- [#656](https://github.com/wycats/handlebars.js/issues/656) - Expose COMPILER_REVISION checks as a hook ([@machty](https://api.github.com/users/machty))
- [#668](https://github.com/wycats/handlebars.js/issues/668) - Consider publishing handlebars-runtime as a separate module on npm ([@dlmanning](https://api.github.com/users/dlmanning))
- [#679](https://github.com/wycats/handlebars.js/issues/679) - Unable to override invokePartial ([@mattbrailsford](https://api.github.com/users/mattbrailsford))
- [#646](https://github.com/wycats/handlebars.js/pull/646) - Fix "\\{{" immediately following "\{{" ([@dmarcotte](https://api.github.com/users/dmarcotte))
- Allow extend to work with non-prototyped objects - eb53f2e
- Add JavascriptCompiler public API tests - 1a751b2
- Add AST test coverage for more complex paths - ddea5be
- Fix handling of boolean escape in MustacheNode - b4968bb
Compatibility notes:
- `@index` and `@first` are now supported for `each` iteration on objects
- `Handlebars.VM.checkRevision` and `Handlebars.JavaScriptCompiler.prototype.compilerInfo` now available to modify the version checking behavior.
- Browserify users may link to the runtime library via `require('handlebars/runtime')`
[Commits](https://github.com/wycats/handlebars.js/compare/v1.1.2...v1.2.0)
## v1.1.2 - November 5th, 2013
- [#645](https://github.com/wycats/handlebars.js/issues/645) - 1.1.1 fails under IE8 ([@kpdecker](https://api.github.com/users/kpdecker))
- [#644](https://github.com/wycats/handlebars.js/issues/644) - Using precompiled templates (AMD mode) with handlebars.runtime 1.1.1 ([@fddima](https://api.github.com/users/fddima))
- Add simple binary utility tests - 96a45a4
- Fix empty string compilation - eea708a
[Commits](https://github.com/wycats/handlebars.js/compare/v1.1.1...v1.1.2)
## v1.1.1 - November 4th, 2013
- [#642](https://github.com/wycats/handlebars.js/issues/642) - handlebars 1.1.0 are broken with nodejs
- Fix release notes link - 17ba258
[Commits](https://github.com/wycats/handlebars.js/compare/v1.1.0...v1.1.1)
## v1.1.0 - November 3rd, 2013
@@ -27,7 +260,7 @@ Compatibility notes:
- AMD: Users may load the bundled `handlebars.amd.js` or `handlebars.runtime.amd.js` files or load individual modules directly. AMD users should also note that the handlebars object is exposed via the `default` field on the imported object. This [gist](https://gist.github.com/wycats/7417be0dc361a69d5916) provides some discussion of possible compatibility shims.
- CommonJS/Node: Node loading occurs as normal via `require`
- Globals: The `handlebars.js` and `handlebars.runtime.js` files should behave in the same manner as the v1.0.12 / 1.0.0 release.
- Build artifacts have been removed from the repository. [npm][npm], [components/handlebars.js][components], [cdnjs][cdnjs-lib], or the [builds page][builds-page] should now be used as the source of built artifacts.
- Build artifacts have been removed from the repository. [npm][npm], [components/handlebars.js][components], [cdnjs][cdnjs], or the [builds page][builds-page] should now be used as the source of built artifacts.
- Context-stored helpers are now always passed the `options` hash. Previously no-argument helpers did not have this argument.
@@ -124,6 +357,6 @@ template(context, {helpers: helpers, partials: partials, data: data})
```
[builds-page]: http://builds.handlebarsjs.com.s3.amazonaws.com/index.html
[cdn-js]: http://cdnjs.com/libraries/handlebars.js/
[cdnjs]: http://cdnjs.com/libraries/handlebars.js/
[components]: https://github.com/components/handlebars.js
[npm]: https://npmjs.org/package/handlebars
+3
View File
@@ -0,0 +1,3 @@
// Create a simple path alias to allow browserify to resolve
// the runtime on a supported path.
module.exports = require('./dist/cjs/handlebars.runtime')['default'];
+89
View File
@@ -0,0 +1,89 @@
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/node_modules/mocha/mocha.css" />
<style>
.headless .suite > h1,
.headless .test.pass {
display: none;
}
</style>
<script>
// Show only errors in "headless", non-interactive mode.
if (/headless=true/.test(location.href)) {
document.documentElement.className = 'headless';
}
</script>
<script src="/node_modules/mocha/mocha.js"></script>
<script>
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>
<script>
requirejs.config({
paths: {
'handlebars.runtime': '/dist/handlebars.runtime.amd'
}
});
</script>
<script>
onload = function(){
require(['handlebars.runtime'], function(Handlebars) {
describe('runtime', function() {
it('should load', function() {
equal(!!Handlebars['default'].template, true);
equal(!!Handlebars['default'].VERSION, true);
});
});
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();
}
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>
<body>
<div id="mocha"></div>
</body>
</html>
+109
View File
@@ -0,0 +1,109 @@
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/node_modules/mocha/mocha.css" />
<style>
.headless .suite > h1,
.headless .test.pass {
display: none;
}
</style>
<script>
// Show only errors in "headless", non-interactive mode.
if (/headless=true/.test(location.href)) {
document.documentElement.className = 'headless';
}
</script>
<script src="/node_modules/mocha/mocha.js"></script>
<script>
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>
<script>
requirejs.config({
paths: {
handlebars: '/dist/handlebars.amd',
tests: '/tmp/tests'
}
});
var CompilerContext = {
compile: function(template, options) {
var templateSpec = handlebarsEnv.precompile(template, options);
return handlebarsEnv.template(safeEval(templateSpec));
},
compileWithPartial: function(template, options) {
return handlebarsEnv.compile(template, options);
}
};
function safeEval(templateSpec) {
try {
var ret;
eval('ret = ' + templateSpec);
return ret;
} catch (err) {
console.error(templateSpec);
throw err;
}
}
</script>
<script>
onload = function(){
require(['handlebars'], function(Handlebars) {
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();
}
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>
<body>
<div id="mocha"></div>
</body>
</html>
+1
View File
@@ -0,0 +1 @@
a
View File
+292
View File
@@ -0,0 +1,292 @@
/*global Handlebars, handlebarsEnv, shouldThrow */
describe('ast', function() {
if (!Handlebars.AST) {
return;
}
var LOCATION_INFO = {
start: {
line: 1,
column: 1
},
end: {
line: 1,
column: 1
}
};
function testLocationInfoStorage(node){
equals(node.loc.start.line, 1);
equals(node.loc.start.column, 1);
equals(node.loc.end.line, 1);
equals(node.loc.end.column, 1);
}
describe('MustacheStatement', function() {
it('should store args', function() {
var id = {isSimple: true},
hash = {},
mustache = new handlebarsEnv.AST.MustacheStatement({}, null, null, true, {}, LOCATION_INFO);
equals(mustache.type, 'MustacheStatement');
equals(mustache.escaped, true);
testLocationInfoStorage(mustache);
});
});
describe('BlockStatement', function() {
it('should throw on mustache mismatch', function() {
shouldThrow(function() {
handlebarsEnv.parse("\n {{#foo}}{{/bar}}");
}, Handlebars.Exception, "foo doesn't match bar - 2:5");
});
it('stores location info', function(){
var mustacheNode = new handlebarsEnv.AST.MustacheStatement([{ original: 'foo'}], null, null, false, {});
var block = new handlebarsEnv.AST.BlockStatement(
mustacheNode,
null, null,
{body: []},
{body: []},
{},
{},
{},
LOCATION_INFO);
testLocationInfoStorage(block);
});
});
describe('PathExpression', function() {
it('stores location info', function(){
var idNode = new handlebarsEnv.AST.PathExpression(false, 0, [], 'foo', LOCATION_INFO);
testLocationInfoStorage(idNode);
});
});
describe('Hash', function(){
it('stores location info', function(){
var hash = new handlebarsEnv.AST.Hash([], LOCATION_INFO);
testLocationInfoStorage(hash);
});
});
describe('ContentStatement', function(){
it('stores location info', function(){
var content = new handlebarsEnv.AST.ContentStatement("HI", LOCATION_INFO);
testLocationInfoStorage(content);
});
});
describe('CommentStatement', function(){
it('stores location info', function(){
var comment = new handlebarsEnv.AST.CommentStatement("HI", {}, LOCATION_INFO);
testLocationInfoStorage(comment);
});
});
describe('NumberLiteral', function(){
it('stores location info', function(){
var integer = new handlebarsEnv.AST.NumberLiteral("6", LOCATION_INFO);
testLocationInfoStorage(integer);
});
});
describe('StringLiteral', function(){
it('stores location info', function(){
var string = new handlebarsEnv.AST.StringLiteral("6", LOCATION_INFO);
testLocationInfoStorage(string);
});
});
describe('BooleanLiteral', function(){
it('stores location info', function(){
var bool = new handlebarsEnv.AST.BooleanLiteral("true", LOCATION_INFO);
testLocationInfoStorage(bool);
});
});
describe('PartialStatement', function(){
it('stores location info', function(){
var pn = new handlebarsEnv.AST.PartialStatement('so_partial', [], {}, {}, LOCATION_INFO);
testLocationInfoStorage(pn);
});
});
describe('Program', function(){
it('storing location info', function(){
var pn = new handlebarsEnv.AST.Program([], null, {}, LOCATION_INFO);
testLocationInfoStorage(pn);
});
});
describe("Line Numbers", function(){
var ast, body;
function testColumns(node, firstLine, lastLine, firstColumn, lastColumn){
equals(node.loc.start.line, firstLine);
equals(node.loc.start.column, firstColumn);
equals(node.loc.end.line, lastLine);
equals(node.loc.end.column, lastColumn);
}
ast = Handlebars.parse("line 1 {{line1Token}}\n line 2 {{line2token}}\n line 3 {{#blockHelperOnLine3}}\nline 4{{line4token}}\n" +
"line5{{else}}\n{{line6Token}}\n{{/blockHelperOnLine3}}");
body = ast.body;
it('gets ContentNode line numbers', function(){
var contentNode = body[0];
testColumns(contentNode, 1, 1, 0, 7);
});
it('gets MustacheStatement line numbers', function(){
var mustacheNode = body[1];
testColumns(mustacheNode, 1, 1, 7, 21);
});
it('gets line numbers correct when newlines appear', function(){
testColumns(body[2], 1, 2, 21, 8);
});
it('gets MustacheStatement line numbers correct across newlines', function(){
var secondMustacheStatement = body[3];
testColumns(secondMustacheStatement, 2, 2, 8, 22);
});
it('gets the block helper information correct', function(){
var blockHelperNode = body[5];
testColumns(blockHelperNode, 3, 7, 8, 23);
});
it('correctly records the line numbers the program of a block helper', function(){
var blockHelperNode = body[5],
program = blockHelperNode.program;
testColumns(program, 3, 5, 8, 5);
});
it('correctly records the line numbers of an inverse of a block helper', function(){
var blockHelperNode = body[5],
inverse = blockHelperNode.inverse;
testColumns(inverse, 5, 7, 5, 0);
});
});
describe('standalone flags', function(){
describe('mustache', function() {
it('does not mark mustaches as standalone', function() {
var ast = Handlebars.parse(' {{comment}} ');
equals(!!ast.body[0].value, true);
equals(!!ast.body[2].value, true);
});
});
describe('blocks', function() {
it('marks block mustaches as standalone', function() {
var ast = Handlebars.parse(' {{# comment}} \nfoo\n {{else}} \n bar \n {{/comment}} '),
block = ast.body[1];
equals(ast.body[0].value, '');
equals(block.program.body[0].value, 'foo\n');
equals(block.inverse.body[0].value, ' bar \n');
equals(ast.body[2].value, '');
});
it('marks initial block mustaches as standalone', function() {
var ast = Handlebars.parse('{{# comment}} \nfoo\n {{/comment}}'),
block = ast.body[0];
equals(block.program.body[0].value, 'foo\n');
});
it('marks mustaches with children as standalone', function() {
var ast = Handlebars.parse('{{# comment}} \n{{foo}}\n {{/comment}}'),
block = ast.body[0];
equals(block.program.body[0].value, '');
equals(block.program.body[1].path.original, 'foo');
equals(block.program.body[2].value, '\n');
});
it('marks nested block mustaches as standalone', function() {
var ast = Handlebars.parse('{{#foo}} \n{{# comment}} \nfoo\n {{else}} \n bar \n {{/comment}} \n{{/foo}}'),
body = ast.body[0].program.body,
block = body[1];
equals(body[0].value, '');
equals(block.program.body[0].value, 'foo\n');
equals(block.inverse.body[0].value, ' bar \n');
equals(body[0].value, '');
});
it('does not mark nested block mustaches as standalone', function() {
var ast = Handlebars.parse('{{#foo}} {{# comment}} \nfoo\n {{else}} \n bar \n {{/comment}} {{/foo}}'),
body = ast.body[0].program.body,
block = body[1];
equals(body[0].omit, undefined);
equals(block.program.body[0].value, ' \nfoo\n');
equals(block.inverse.body[0].value, ' bar \n ');
equals(body[0].omit, undefined);
});
it('does not mark nested initial block mustaches as standalone', function() {
var ast = Handlebars.parse('{{#foo}}{{# comment}} \nfoo\n {{else}} \n bar \n {{/comment}}{{/foo}}'),
body = ast.body[0].program.body,
block = body[0];
equals(block.program.body[0].value, ' \nfoo\n');
equals(block.inverse.body[0].value, ' bar \n ');
equals(body[0].omit, undefined);
});
it('marks column 0 block mustaches as standalone', function() {
var ast = Handlebars.parse('test\n{{# comment}} \nfoo\n {{else}} \n bar \n {{/comment}} '),
block = ast.body[1];
equals(ast.body[0].omit, undefined);
equals(block.program.body[0].value, 'foo\n');
equals(block.inverse.body[0].value, ' bar \n');
equals(ast.body[2].value, '');
});
});
describe('partials', function() {
it('marks partial as standalone', function() {
var ast = Handlebars.parse('{{> partial }} ');
equals(ast.body[1].value, '');
});
it('marks indented partial as standalone', function() {
var ast = Handlebars.parse(' {{> partial }} ');
equals(ast.body[0].value, '');
equals(ast.body[1].indent, ' ');
equals(ast.body[2].value, '');
});
it('marks those around content as not standalone', function() {
var ast = Handlebars.parse('a{{> partial }}');
equals(ast.body[0].omit, undefined);
ast = Handlebars.parse('{{> partial }}a');
equals(ast.body[1].omit, undefined);
});
});
describe('comments', function() {
it('marks comment as standalone', function() {
var ast = Handlebars.parse('{{! comment }} ');
equals(ast.body[1].value, '');
});
it('marks indented comment as standalone', function() {
var ast = Handlebars.parse(' {{! comment }} ');
equals(ast.body[0].value, '');
equals(ast.body[2].value, '');
});
it('marks those around content as not standalone', function() {
var ast = Handlebars.parse('a{{! comment }}');
equals(ast.body[0].omit, undefined);
ast = Handlebars.parse('{{! comment }}a');
equals(ast.body[1].omit, undefined);
});
});
});
});
+77 -4
View File
@@ -1,3 +1,4 @@
/*global CompilerContext, Handlebars, beforeEach, shouldCompileTo, shouldThrow */
global.handlebarsEnv = null;
beforeEach(function() {
@@ -32,6 +33,13 @@ describe("basic context", function() {
shouldCompileTo("{{! Goodbye}}Goodbye\n{{cruel}}\n{{world}}!",
{cruel: "cruel", world: "world"}, "Goodbye\ncruel\nworld!",
"comments are ignored");
shouldCompileTo(' {{~! comment ~}} blah', {}, 'blah');
shouldCompileTo(' {{~!-- long-comment --~}} blah', {}, 'blah');
shouldCompileTo(' {{! comment ~}} blah', {}, ' blah');
shouldCompileTo(' {{!-- long-comment --~}} blah', {}, ' blah');
shouldCompileTo(' {{~! comment}} blah', {}, ' blah');
shouldCompileTo(' {{~!-- long-comment --}} blah', {}, ' blah');
});
it("boolean", function() {
@@ -49,6 +57,14 @@ describe("basic context", function() {
shouldCompileTo("num: {{.}}", 0, "num: 0");
shouldCompileTo("num: {{num1/num2}}", {num1: {num2: 0}}, "num: 0");
});
it('false', function() {
shouldCompileTo('val1: {{val1}}, val2: {{val2}}', {val1: false, val2: new Boolean(false)}, 'val1: false, val2: false');
shouldCompileTo('val: {{.}}', false, 'val: false');
shouldCompileTo('val: {{val1/val2}}', {val1: {val2: false}}, 'val: false');
shouldCompileTo('val1: {{{val1}}}, val2: {{{val2}}}', {val1: false, val2: new Boolean(false)}, 'val1: false, val2: false');
shouldCompileTo('val: {{{val1/val2}}}', {val1: {val2: false}}, 'val: false');
});
it("newlines", function() {
shouldCompileTo("Alan's\nTest", {}, "Alan's\nTest");
@@ -96,6 +112,18 @@ describe("basic context", function() {
frank: "Frank"},
"Frank", "functions are called with context arguments");
});
it("pathed functions with context argument", function() {
shouldCompileTo("{{bar.awesome frank}}",
{bar: {awesome: function(context) { return context; }},
frank: "Frank"},
"Frank", "functions are called with context arguments");
});
it("depthed functions with context argument", function() {
shouldCompileTo("{{#with frank}}{{../awesome .}}{{/with}}",
{awesome: function(context) { return context; },
frank: "Frank"},
"Frank", "functions are called with context arguments");
});
it("block functions with context argument", function() {
shouldCompileTo("{{#awesome 1}}inner {{.}}{{/awesome}}",
@@ -103,11 +131,27 @@ describe("basic context", function() {
"inner 1", "block functions are called with context and options");
});
it("depthed block functions with context argument", function() {
shouldCompileTo("{{#with value}}{{#../awesome 1}}inner {{.}}{{/../awesome}}{{/with}}",
{value: true, awesome: function(context, options) { return options.fn(context); }},
"inner 1", "block functions are called with context and options");
});
it("block functions without context argument", function() {
shouldCompileTo("{{#awesome}}inner{{/awesome}}",
{awesome: function(options) { return options.fn(this); }},
"inner", "block functions are called with options");
});
it("pathed block functions without context argument", function() {
shouldCompileTo("{{#foo.awesome}}inner{{/foo.awesome}}",
{foo: {awesome: function() { return this; }}},
"inner", "block functions are called with options");
});
it("depthed block functions without context argument", function() {
shouldCompileTo("{{#with value}}{{#../awesome}}inner{{/../awesome}}{{/with}}",
{value: true, awesome: function() { return this; }},
"inner", "block functions are called with options");
});
it("paths with hyphens", function() {
@@ -160,9 +204,9 @@ describe("basic context", function() {
it("this keyword nested inside path", function() {
var string = "{{#hellos}}{{text/this/foo}}{{/hellos}}";
(function() {
shouldThrow(function() {
CompilerContext.compile(string);
}).should.throw(Error);
}, Error);
});
it("this keyword in helpers", function() {
@@ -181,8 +225,37 @@ describe("basic context", function() {
it("this keyword nested inside helpers param", function() {
var string = "{{#hellos}}{{foo text/this/foo}}{{/hellos}}";
(function() {
shouldThrow(function() {
CompilerContext.compile(string);
}).should.throw(Error);
}, Error);
});
it('pass string literals', function() {
shouldCompileTo('{{"foo"}}', {}, '');
shouldCompileTo('{{"foo"}}', { foo: 'bar' }, 'bar');
shouldCompileTo('{{#"foo"}}{{.}}{{/"foo"}}', { foo: ['bar', 'baz'] }, 'barbaz');
});
it('pass number literals', function() {
shouldCompileTo('{{12}}', {}, '');
shouldCompileTo('{{12}}', { '12': 'bar' }, 'bar');
shouldCompileTo('{{12.34}}', {}, '');
shouldCompileTo('{{12.34}}', { '12.34': 'bar' }, 'bar');
shouldCompileTo('{{12.34 1}}', { '12.34': function(arg) { return 'bar' + arg; } }, 'bar1');
});
it('pass boolean literals', function() {
shouldCompileTo('{{true}}', {}, '');
shouldCompileTo('{{true}}', { '': 'foo' }, '');
shouldCompileTo('{{false}}', { 'false': 'foo' }, 'foo');
});
it('should handle literals in subexpression', function() {
var helpers = {
foo: function(arg) {
return arg;
}
};
shouldCompileTo('{{foo (false)}}', [{ 'false': function() { return 'bar'; } }, helpers], 'bar');
});
});
+74 -7
View File
@@ -1,4 +1,4 @@
/*global CompilerContext, shouldCompileTo */
/*global CompilerContext, shouldCompileTo, shouldThrow */
describe('blocks', function() {
it("array", function() {
var string = "{{#goodbyes}}{{text}}! {{/goodbyes}}cruel {{world}}!";
@@ -8,7 +8,12 @@ describe('blocks', function() {
shouldCompileTo(string, {goodbyes: [], world: "world"}, "cruel world!",
"Arrays ignore the contents when empty");
});
it('array without data', function() {
var string = '{{#goodbyes}}{{text}}{{/goodbyes}} {{#goodbyes}}{{text}}{{/goodbyes}}';
var hash = {goodbyes: [{text: 'goodbye'}, {text: 'Goodbye'}, {text: 'GOODBYE'}], world: 'world'};
shouldCompileTo(string, [hash,,,,false], 'goodbyeGoodbyeGOODBYE goodbyeGoodbyeGOODBYE');
});
it("array with @index", function() {
@@ -20,7 +25,7 @@ describe('blocks', function() {
equal(result, "0. goodbye! 1. Goodbye! 2. GOODBYE! cruel world!", "The @index variable is used");
});
it("empty block", function() {
var string = "{{#goodbyes}}{{/goodbyes}}cruel {{world}}!";
var hash = {goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}], world: "world"};
@@ -39,19 +44,26 @@ describe('blocks', function() {
"Templates can access variables in contexts up the stack with relative path syntax");
});
it('multiple blocks with complex lookup', function() {
var string = '{{#goodbyes}}{{../name}}{{../name}}{{/goodbyes}}';
var hash = {name: 'Alan', goodbyes: [{text: 'goodbye'}, {text: 'Goodbye'}, {text: 'GOODBYE'}]};
shouldCompileTo(string, hash, 'AlanAlanAlanAlanAlanAlan');
});
it("block with complex lookup using nested context", function() {
var string = "{{#goodbyes}}{{text}} cruel {{foo/../name}}! {{/goodbyes}}";
(function() {
shouldThrow(function() {
CompilerContext.compile(string);
}).should.throw(Error);
}, Error);
});
it("block with deep nested complex lookup", function() {
var string = "{{#outer}}Goodbye {{#inner}}cruel {{../../omg}}{{/inner}}{{/outer}}";
var hash = {omg: "OMG!", outer: [{ inner: [{ text: "goodbye" }] }] };
var string = "{{#outer}}Goodbye {{#inner}}cruel {{../sibling}} {{../../omg}}{{/inner}}{{/outer}}";
var hash = {omg: "OMG!", outer: [{ sibling: 'sad', inner: [{ text: "goodbye" }] }] };
shouldCompileTo(string, hash, "Goodbye cruel OMG!");
shouldCompileTo(string, hash, "Goodbye cruel sad OMG!");
});
describe('inverted sections', function() {
@@ -77,10 +89,65 @@ describe('blocks', function() {
shouldCompileTo("{{#people}}{{name}}{{^}}{{none}}{{/people}}", {none: "No people"},
"No people");
});
it("chained inverted sections", function() {
shouldCompileTo("{{#people}}{{name}}{{else if none}}{{none}}{{/people}}", {none: "No people"},
"No people");
shouldCompileTo("{{#people}}{{name}}{{else if nothere}}fail{{else unless nothere}}{{none}}{{/people}}", {none: "No people"},
"No people");
shouldCompileTo("{{#people}}{{name}}{{else if none}}{{none}}{{else}}fail{{/people}}", {none: "No people"},
"No people");
});
it("chained inverted sections with mismatch", function() {
shouldThrow(function() {
shouldCompileTo("{{#people}}{{name}}{{else if none}}{{none}}{{/if}}", {none: "No people"},
"No people");
}, Error);
});
it("block inverted sections with empty arrays", function() {
shouldCompileTo("{{#people}}{{name}}{{^}}{{none}}{{/people}}", {none: "No people", people: []},
"No people");
});
});
describe('standalone sections', function() {
it('block standalone else sections', function() {
shouldCompileTo('{{#people}}\n{{name}}\n{{^}}\n{{none}}\n{{/people}}\n', {none: 'No people'},
'No people\n');
shouldCompileTo('{{#none}}\n{{.}}\n{{^}}\n{{none}}\n{{/none}}\n', {none: 'No people'},
'No people\n');
shouldCompileTo('{{#people}}\n{{name}}\n{{^}}\n{{none}}\n{{/people}}\n', {none: 'No people'},
'No people\n');
});
it('block standalone chained else sections', function() {
shouldCompileTo('{{#people}}\n{{name}}\n{{else if none}}\n{{none}}\n{{/people}}\n', {none: 'No people'},
'No people\n');
shouldCompileTo('{{#people}}\n{{name}}\n{{else if none}}\n{{none}}\n{{^}}\n{{/people}}\n', {none: 'No people'},
'No people\n');
});
it('should handle nesting', function() {
shouldCompileTo('{{#data}}\n{{#if true}}\n{{.}}\n{{/if}}\n{{/data}}\nOK.', {data: [1, 3, 5]}, '1\n3\n5\nOK.');
});
});
describe('compat mode', function() {
it("block with deep recursive lookup lookup", function() {
var string = "{{#outer}}Goodbye {{#inner}}cruel {{omg}}{{/inner}}{{/outer}}";
var hash = {omg: "OMG!", outer: [{ inner: [{ text: "goodbye" }] }] };
shouldCompileTo(string, [hash, undefined, undefined, true], "Goodbye cruel OMG!");
});
it("block with deep recursive pathed lookup", function() {
var string = "{{#outer}}Goodbye {{#inner}}cruel {{omg.yes}}{{/inner}}{{/outer}}";
var hash = {omg: {yes: "OMG!"}, outer: [{ inner: [{ yes: 'no', text: "goodbye" }] }] };
shouldCompileTo(string, [hash, undefined, undefined, true], "Goodbye cruel OMG!");
});
it("block with missed recursive lookup", function() {
var string = "{{#outer}}Goodbye {{#inner}}cruel {{omg.yes}}{{/inner}}{{/outer}}";
var hash = {omg: {no: "OMG!"}, outer: [{ inner: [{ yes: 'no', text: "goodbye" }] }] };
shouldCompileTo(string, [hash, undefined, undefined, true], "Goodbye cruel ");
});
});
});
+178 -13
View File
@@ -1,4 +1,4 @@
/*global CompilerContext, shouldCompileTo, compileWithPartials */
/*global CompilerContext, shouldCompileTo, shouldThrow, compileWithPartials, handlebarsEnv */
describe('builtin helpers', function() {
describe('#if', function() {
it("if", function() {
@@ -44,6 +44,10 @@ describe('builtin helpers', function() {
var string = "{{#with person}}{{first}} {{last}}{{/with}}";
shouldCompileTo(string, {person: function() { return {first: "Alan", last: "Johnson"};}}, "Alan Johnson");
});
it("with with else", function() {
var string = "{{#with person}}Person is present{{else}}Person is not present{{/with}}";
shouldCompileTo(string, {}, "Person is not present");
});
});
describe('#each', function() {
@@ -62,9 +66,29 @@ describe('builtin helpers', function() {
"each with array argument ignores the contents when empty");
});
it('each without data', function() {
var string = '{{#each goodbyes}}{{text}}! {{/each}}cruel {{world}}!';
var hash = {goodbyes: [{text: 'goodbye'}, {text: 'Goodbye'}, {text: 'GOODBYE'}], world: 'world'};
shouldCompileTo(string, [hash,,,,false], 'goodbye! Goodbye! GOODBYE! cruel world!');
hash = {goodbyes: 'cruel', world: 'world'};
shouldCompileTo('{{#each .}}{{.}}{{/each}}', [hash,,,,false], 'cruelworld');
});
it('each without context', function() {
var string = '{{#each goodbyes}}{{text}}! {{/each}}cruel {{world}}!';
shouldCompileTo(string, [,,,,], 'cruel !');
});
it("each with an object and @key", function() {
var string = "{{#each goodbyes}}{{@key}}. {{text}}! {{/each}}cruel {{world}}!";
var hash = {goodbyes: {"<b>#1</b>": {text: "goodbye"}, 2: {text: "GOODBYE"}}, world: "world"};
function Clazz() {
this['<b>#1</b>'] = {text: 'goodbye'};
this[2] = {text: 'GOODBYE'};
}
Clazz.prototype.foo = 'fail';
var hash = {goodbyes: new Clazz(), world: 'world'};
// Object property iteration order is undefined according to ECMA spec,
// so we need to check both possible orders
@@ -73,9 +97,8 @@ describe('builtin helpers', function() {
var expected1 = "&lt;b&gt;#1&lt;/b&gt;. goodbye! 2. GOODBYE! cruel world!";
var expected2 = "2. GOODBYE! &lt;b&gt;#1&lt;/b&gt;. goodbye! cruel world!";
(actual === expected1 || actual === expected2).should.equal(true, "each with object argument iterates over the contents when not empty");
shouldCompileTo(string, {goodbyes: [], world: "world"}, "cruel world!",
"each with object argument ignores the contents when empty");
equals(actual === expected1 || actual === expected2, true, "each with object argument iterates over the contents when not empty");
shouldCompileTo(string, {goodbyes: {}, world: 'world'}, 'cruel world!');
});
it("each with @index", function() {
@@ -98,6 +121,27 @@ describe('builtin helpers', function() {
equal(result, "0. goodbye! 0 1 2 After 0 1. Goodbye! 0 1 2 After 1 2. GOODBYE! 0 1 2 After 2 cruel world!", "The @index variable is used");
});
it('each with block params', function() {
var string = '{{#each goodbyes as |value index|}}{{index}}. {{value.text}}! {{#each ../goodbyes as |childValue childIndex|}} {{index}} {{childIndex}}{{/each}} After {{index}} {{/each}}{{index}}cruel {{world}}!';
var hash = {goodbyes: [{text: 'goodbye'}, {text: 'Goodbye'}], world: 'world'};
var template = CompilerContext.compile(string);
var result = template(hash);
equal(result, '0. goodbye! 0 0 0 1 After 0 1. Goodbye! 1 0 1 1 After 1 cruel world!');
});
it("each object with @index", function() {
var string = "{{#each goodbyes}}{{@index}}. {{text}}! {{/each}}cruel {{world}}!";
var hash = {goodbyes: {'a': {text: "goodbye"}, b: {text: "Goodbye"}, c: {text: "GOODBYE"}}, world: "world"};
var template = CompilerContext.compile(string);
var result = template(hash);
equal(result, "0. goodbye! 1. Goodbye! 2. GOODBYE! cruel world!", "The @index variable is used");
});
it("each with @first", function() {
var string = "{{#each goodbyes}}{{#if @first}}{{text}}! {{/if}}{{/each}}cruel {{world}}!";
var hash = {goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}], world: "world"};
@@ -118,6 +162,16 @@ describe('builtin helpers', function() {
equal(result, "(goodbye! goodbye! goodbye!) (goodbye!) (goodbye!) cruel world!", "The @first variable is used");
});
it("each object with @first", function() {
var string = "{{#each goodbyes}}{{#if @first}}{{text}}! {{/if}}{{/each}}cruel {{world}}!";
var hash = {goodbyes: {'foo': {text: "goodbye"}, bar: {text: "Goodbye"}}, world: "world"};
var template = CompilerContext.compile(string);
var result = template(hash);
equal(result, "goodbye! cruel world!", "The @first variable is used");
});
it("each with @last", function() {
var string = "{{#each goodbyes}}{{#if @last}}{{text}}! {{/if}}{{/each}}cruel {{world}}!";
var hash = {goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}], world: "world"};
@@ -128,6 +182,16 @@ describe('builtin helpers', function() {
equal(result, "GOODBYE! cruel world!", "The @last variable is used");
});
it("each object with @last", function() {
var string = "{{#each goodbyes}}{{#if @last}}{{text}}! {{/if}}{{/each}}cruel {{world}}!";
var hash = {goodbyes: {'foo': {text: "goodbye"}, bar: {text: "Goodbye"}}, world: "world"};
var template = CompilerContext.compile(string);
var result = template(hash);
equal(result, "Goodbye! cruel world!", "The @last variable is used");
});
it("each with nested @last", function() {
var string = "{{#each goodbyes}}({{#if @last}}{{text}}! {{/if}}{{#each ../goodbyes}}{{#if @last}}{{text}}!{{/if}}{{/each}}{{#if @last}} {{text}}!{{/if}}) {{/each}}cruel {{world}}!";
var hash = {goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}], world: "world"};
@@ -160,19 +224,120 @@ describe('builtin helpers', function() {
equal(result, 'a!b!c!', 'should output data');
});
it("each on implicit context", function() {
shouldThrow(function() {
var template = CompilerContext.compile("{{#each}}{{text}}! {{/each}}cruel world!");
template({});
}, handlebarsEnv.Exception, 'Must pass iterator to #each');
});
});
it("#log", function() {
describe("#log", function() {
if (typeof console === 'undefined') {
return;
}
var string = "{{log blah}}";
var hash = { blah: "whee" };
var log,
info,
error;
beforeEach(function() {
log = console.log;
info = console.info;
error = console.error;
});
afterEach(function() {
console.log = log;
console.info = info;
console.error = error;
});
var levelArg, logArg;
handlebarsEnv.log = function(level, arg){ levelArg = level, logArg = arg; };
it('should call logger at default level', function() {
var string = "{{log blah}}";
var hash = { blah: "whee" };
shouldCompileTo(string, hash, "", "log should not display");
equals(1, levelArg, "should call log with 1");
equals("whee", logArg, "should call log with 'whee'");
var levelArg, logArg;
handlebarsEnv.log = function(level, arg){
levelArg = level;
logArg = arg;
};
shouldCompileTo(string, hash, "", "log should not display");
equals(1, levelArg, "should call log with 1");
equals("whee", logArg, "should call log with 'whee'");
});
it('should call logger at data level', function() {
var string = "{{log blah}}";
var hash = { blah: "whee" };
var levelArg, logArg;
handlebarsEnv.log = function(level, arg){
levelArg = level;
logArg = arg;
};
shouldCompileTo(string, [hash,,,,{level: '03'}], "");
equals(3, levelArg);
equals("whee", logArg);
});
it('should output to info', function() {
var string = "{{log blah}}";
var hash = { blah: "whee" };
var called;
console.info = function(log) {
equals("whee", log);
called = true;
};
console.log = function(log) {
equals("whee", log);
called = true;
};
shouldCompileTo(string, hash, "");
equals(true, called);
});
it('should log at data level', function() {
var string = "{{log blah}}";
var hash = { blah: "whee" };
var called;
console.error = function(log) {
equals("whee", log);
called = true;
};
shouldCompileTo(string, [hash,,,,{level: '03'}], "");
equals(true, called);
});
it('should handle missing logger', function() {
var string = "{{log blah}}";
var hash = { blah: "whee" };
console.error = undefined;
shouldCompileTo(string, [hash,,,,{level: '03'}], "");
});
});
describe('#lookup', function() {
it('should lookup arbitrary content', function() {
var string = '{{#each goodbyes}}{{lookup ../data .}}{{/each}}',
hash = {goodbyes: [0, 1], data: ['foo', 'bar']};
var template = CompilerContext.compile(string);
var result = template(hash);
equal(result, 'foobar');
});
it('should not fail on undefined value', function() {
var string = '{{#each goodbyes}}{{lookup ../bar .}}{{/each}}',
hash = {goodbyes: [0, 1], data: ['foo', 'bar']};
var template = CompilerContext.compile(string);
var result = template(hash);
equal(result, '');
});
});
});
+70
View File
@@ -0,0 +1,70 @@
/*global Handlebars, shouldThrow */
describe('compiler', function() {
if (!Handlebars.compile) {
return;
}
describe('#equals', function() {
function compile(string) {
var ast = Handlebars.parse(string);
return new Handlebars.Compiler().compile(ast, {});
}
it('should treat as equal', function() {
equal(compile('foo').equals(compile('foo')), true);
equal(compile('{{foo}}').equals(compile('{{foo}}')), true);
equal(compile('{{foo.bar}}').equals(compile('{{foo.bar}}')), true);
equal(compile('{{foo.bar baz "foo" true false bat=1}}').equals(compile('{{foo.bar baz "foo" true false bat=1}}')), true);
equal(compile('{{foo.bar (baz bat=1)}}').equals(compile('{{foo.bar (baz bat=1)}}')), true);
equal(compile('{{#foo}} {{/foo}}').equals(compile('{{#foo}} {{/foo}}')), true);
});
it('should treat as not equal', function() {
equal(compile('foo').equals(compile('bar')), false);
equal(compile('{{foo}}').equals(compile('{{bar}}')), false);
equal(compile('{{foo.bar}}').equals(compile('{{bar.bar}}')), false);
equal(compile('{{foo.bar baz bat=1}}').equals(compile('{{foo.bar bar bat=1}}')), false);
equal(compile('{{foo.bar (baz bat=1)}}').equals(compile('{{foo.bar (bar bat=1)}}')), false);
equal(compile('{{#foo}} {{/foo}}').equals(compile('{{#bar}} {{/bar}}')), false);
equal(compile('{{#foo}} {{/foo}}').equals(compile('{{#foo}} {{foo}}{{/foo}}')), false);
});
});
describe('#compile', function() {
it('should fail with invalid input', function() {
shouldThrow(function() {
Handlebars.compile(null);
}, Error, 'You must pass a string or Handlebars AST to Handlebars.compile. You passed null');
shouldThrow(function() {
Handlebars.compile({});
}, Error, 'You must pass a string or Handlebars AST to Handlebars.compile. You passed [object Object]');
});
it('can utilize AST instance', function() {
equal(Handlebars.compile(new Handlebars.AST.Program([ new Handlebars.AST.ContentStatement("Hello")], null, {}))(), 'Hello');
});
it("can pass through an empty string", function() {
equal(Handlebars.compile('')(), '');
});
});
describe('#precompile', function() {
it('should fail with invalid input', function() {
shouldThrow(function() {
Handlebars.precompile(null);
}, Error, 'You must pass a string or Handlebars AST to Handlebars.precompile. You passed null');
shouldThrow(function() {
Handlebars.precompile({});
}, Error, 'You must pass a string or Handlebars AST to Handlebars.precompile. You passed [object Object]');
});
it('can utilize AST instance', function() {
equal(/return "Hello"/.test(Handlebars.precompile(new Handlebars.AST.Program([ new Handlebars.AST.ContentStatement("Hello")]), null, {})), true);
});
it("can pass through an empty string", function() {
equal(/return ""/.test(Handlebars.precompile('')), true);
});
});
});
+48 -19
View File
@@ -1,4 +1,4 @@
/*global CompilerContext */
/*global CompilerContext, Handlebars, handlebarsEnv, shouldThrow */
describe('data', function() {
it("passing in data to a compiled function that expects data - works with helpers", function() {
var template = CompilerContext.compile("{{hello}}", {data: true});
@@ -85,28 +85,23 @@ describe('data', function() {
equals("Hello undefined", result, "@foo as a parameter retrieves template data");
});
it("parameter data throws when using this scope references", function() {
var string = "{{#goodbyes}}{{text}} cruel {{@./name}}! {{/goodbyes}}";
(function() {
CompilerContext.compile(string);
}).should.throw(Error);
});
it("parameter data throws when using parent scope references", function() {
var string = "{{#goodbyes}}{{text}} cruel {{@../name}}! {{/goodbyes}}";
(function() {
CompilerContext.compile(string);
}).should.throw(Error);
});
it("parameter data throws when using complex scope references", function() {
var string = "{{#goodbyes}}{{text}} cruel {{@foo/../name}}! {{/goodbyes}}";
(function() {
shouldThrow(function() {
CompilerContext.compile(string);
}).should.throw(Error);
}, Error);
});
it('data can be functions', function() {
var template = CompilerContext.compile('{{@hello}}');
var result = template({}, { data: { hello: function() { return 'hello'; } } });
equals('hello', result);
});
it('data can be functions with params', function() {
var template = CompilerContext.compile('{{@hello "hello"}}');
var result = template({}, { data: { hello: function(arg) { return arg; } } });
equals('hello', result);
});
it("data is inherited downstream", function() {
@@ -236,4 +231,38 @@ describe('data', function() {
equals("sad world?", result, "Overriden data output by helper");
});
describe('@root', function() {
it('the root context can be looked up via @root', function() {
var template = CompilerContext.compile('{{@root.foo}}');
var result = template({foo: 'hello'}, { data: {} });
equals('hello', result);
result = template({foo: 'hello'}, {});
equals('hello', result);
});
it('passed root values take priority', function() {
var template = CompilerContext.compile('{{@root.foo}}');
var result = template({}, { data: {root: {foo: 'hello'} } });
equals('hello', result);
});
});
describe('nesting', function() {
it('the root context can be looked up via @root', function() {
var template = CompilerContext.compile('{{#helper}}{{#helper}}{{@./depth}} {{@../depth}} {{@../../depth}}{{/helper}}{{/helper}}');
var result = template({foo: 'hello'}, {
helpers: {
helper: function(options) {
var frame = Handlebars.createFrame(options.data);
frame.depth = options.data.depth + 1;
return options.fn(this, {data: frame});
}
},
data: {
depth: 0
}
});
equals('2 1 0', result);
});
});
});
+9 -2
View File
@@ -5,10 +5,12 @@ var _ = require('underscore'),
fs = require('fs'),
vm = require('vm');
global.Handlebars = undefined;
global.Handlebars = 'no-conflict';
vm.runInThisContext(fs.readFileSync(__dirname + '/../../dist/handlebars.js'), 'dist/handlebars.js');
global.CompilerContext = {
browser: true,
compile: function(template, options) {
var templateSpec = handlebarsEnv.precompile(template, options);
return handlebarsEnv.template(safeEval(templateSpec));
@@ -19,5 +21,10 @@ global.CompilerContext = {
};
function safeEval(templateSpec) {
return eval('(' + templateSpec + ')');
try {
return eval('(' + templateSpec + ')');
} catch (err) {
console.error(templateSpec);
throw err;
}
}
+34 -5
View File
@@ -1,28 +1,57 @@
global.should = require('should');
/*global CompilerContext, compileWithPartials, shouldCompileToWithPartials */
global.shouldCompileTo = function(string, hashOrArray, expected, message) {
shouldCompileToWithPartials(string, hashOrArray, false, expected, message);
};
global.shouldCompileToWithPartials = function(string, hashOrArray, partials, expected, message) {
var result = compileWithPartials(string, hashOrArray, partials);
result.should.equal(expected, "'" + expected + "' should === '" + result + "': " + message);
if (result !== expected) {
throw new Error("'" + result + "' should === '" + expected + "': " + message);
}
};
global.compileWithPartials = function(string, hashOrArray, partials) {
var template = CompilerContext[partials ? 'compileWithPartial' : 'compile'](string), ary;
var template,
ary,
options;
if(Object.prototype.toString.call(hashOrArray) === "[object Array]") {
ary = [];
ary.push(hashOrArray[0]);
ary.push({ helpers: hashOrArray[1], partials: hashOrArray[2] });
options = typeof hashOrArray[3] === 'object' ? hashOrArray[3] : {compat: hashOrArray[3]};
if (hashOrArray[4] != null) {
options.data = !!hashOrArray[4];
ary[1].data = hashOrArray[4];
}
} else {
ary = [hashOrArray];
}
template = CompilerContext[partials ? 'compileWithPartial' : 'compile'](string, options);
return template.apply(this, ary);
};
global.equals = global.equal = function(a, b, msg) {
a.should.equal(b, msg || '');
if (a !== b) {
throw new Error("'" + a + "' should === '" + b + "'" + (msg ? ": " + msg : ''));
}
};
global.shouldThrow = function(callback, type, msg) {
var failed;
try {
callback();
failed = true;
} catch (err) {
if (type && !(err instanceof type)) {
throw new Error('Type failure: ' + err);
}
if (msg && !(msg.test ? msg.test(err.message) : msg === err.message)) {
equal(msg, err.message);
}
}
if (failed) {
throw new Error('It failed to throw');
}
};
+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');
};
}
}());
+6 -1
View File
@@ -14,5 +14,10 @@ global.CompilerContext = {
};
function safeEval(templateSpec) {
return eval('(' + templateSpec + ')');
try {
return eval('(' + templateSpec + ')');
} catch (err) {
console.error(templateSpec);
throw err;
}
}
+2054
View File
File diff suppressed because it is too large Load Diff
+24 -3
View File
@@ -5,14 +5,26 @@ var _ = require('underscore'),
fs = require('fs'),
vm = require('vm');
global.Handlebars = undefined;
global.Handlebars = 'no-conflict';
vm.runInThisContext(fs.readFileSync(__dirname + '/../../dist/handlebars.runtime.js'), 'dist/handlebars.runtime.js');
var parse = require('../../dist/cjs/handlebars/compiler/base').parse;
var compiler = require('../../dist/cjs/handlebars/compiler/compiler');
var JavaScriptCompiler = require('../../dist/cjs/handlebars/compiler/javascript-compiler')['default'];
global.CompilerContext = {
browser: true,
compile: function(template, options) {
var templateSpec = compiler.precompile(template, options);
// Hack the compiler on to the environment for these specific tests
handlebarsEnv.precompile = function(template, options) {
return compiler.precompile(template, options, handlebarsEnv);
};
handlebarsEnv.parse = parse;
handlebarsEnv.Compiler = compiler.Compiler;
handlebarsEnv.JavaScriptCompiler = JavaScriptCompiler;
var templateSpec = handlebarsEnv.precompile(template, options);
return handlebarsEnv.template(safeEval(templateSpec));
},
compileWithPartial: function(template, options) {
@@ -20,10 +32,19 @@ global.CompilerContext = {
handlebarsEnv.compile = function(template, options) {
return compiler.compile(template, options, handlebarsEnv);
};
handlebarsEnv.parse = parse;
handlebarsEnv.Compiler = compiler.Compiler;
handlebarsEnv.JavaScriptCompiler = JavaScriptCompiler;
return handlebarsEnv.compile(template, options);
}
};
function safeEval(templateSpec) {
return eval('(' + templateSpec + ')');
try {
return eval('(' + templateSpec + ')');
} catch (err) {
console.error(templateSpec);
throw err;
}
}
+6
View File
@@ -0,0 +1,6 @@
define(['handlebars.runtime'], function(Handlebars) {
Handlebars = Handlebars["default"]; var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
return templates['empty'] = template({"compiler":[6,">= 2.0.0-beta.1"],"main":function(depth0,helpers,partials,data) {
return "";
},"useData":true});
});
+216 -24
View File
@@ -1,4 +1,4 @@
/*global CompilerContext, shouldCompileTo, shouldCompileToWithPartials */
/*global CompilerContext, Handlebars, shouldCompileTo, shouldCompileToWithPartials, shouldThrow, handlebarsEnv */
describe('helpers', function() {
it("helper with complex lookup$", function() {
var string = "{{#goodbyes}}{{{link ../prefix}}}{{/goodbyes}}";
@@ -9,6 +9,26 @@ describe('helpers', function() {
shouldCompileTo(string, [hash, helpers], "<a href='/root/goodbye'>Goodbye</a>");
});
it("helper for raw block gets raw content", function() {
var string = "{{{{raw}}}} {{test}} {{{{/raw}}}}";
var hash = { test: "hello" };
var helpers = { raw: function(options) {
return options.fn();
} };
shouldCompileTo(string, [hash, helpers], " {{test}} ",
"raw block helper gets raw content");
});
it("helper for raw block gets parameters", function() {
var string = "{{{{raw 1 2 3}}}} {{test}} {{{{/raw}}}}";
var hash = { test: "hello" };
var helpers = { raw: function(a, b, c, options) {
return options.fn() + a + b + c;
} };
shouldCompileTo(string, [hash, helpers], " {{test}} 123",
"raw block helper gets raw content");
});
it("helper block with complex lookup expression", function() {
var string = "{{#goodbyes}}{{../name}}{{/goodbyes}}";
var hash = {name: "Alan"};
@@ -40,6 +60,10 @@ describe('helpers', function() {
}};
shouldCompileToWithPartials(string, [hash, helpers], true, "<a href='/root/goodbye'>Goodbye</a>");
});
it('helper returning undefined value', function() {
shouldCompileTo(' {{nothere}}', [{}, {nothere: function() {}}], ' ');
shouldCompileTo(' {{#nothere}}{{/nothere}}', [{}, {nothere: function() {}}], ' ');
});
it("block helper", function() {
var string = "{{#goodbyes}}{{text}}! {{/goodbyes}}cruel {{world}}!";
@@ -138,6 +162,22 @@ describe('helpers', function() {
shouldCompileTo(messageString, [rootMessage, { list: list }], "<p>Nobody&#x27;s here</p>", "the context of an inverse is the parent of the block");
});
it('pathed lambas with parameters', function() {
var hash = {
helper: function() {
return 'winning';
}
};
hash.hash = hash;
var helpers = {
'./helper': function() {
return 'fail';
}
};
shouldCompileTo('{{./helper 1}}', [hash, helpers], 'winning');
shouldCompileTo('{{hash/helper 1}}', [hash, helpers], 'winning');
});
describe("helpers hash", function() {
it("providing a helpers hash", function() {
shouldCompileTo("Goodbye {{cruel}} {{world}}!", [{cruel: "cruel"}, {world: function() { return "world"; }}], "Goodbye cruel world!",
@@ -172,20 +212,52 @@ describe('helpers', function() {
});
});
it("Multiple global helper registration", function() {
var helpers = handlebarsEnv.helpers;
handlebarsEnv.helpers = {};
describe('registration', function() {
it('unregisters', function() {
var helpers = handlebarsEnv.helpers;
handlebarsEnv.helpers = {};
handlebarsEnv.registerHelper({
'if': helpers['if'],
world: function() { return "world!"; },
test_helper: function() { return 'found it!'; }
handlebarsEnv.registerHelper('foo', function() {
return 'fail';
});
handlebarsEnv.unregisterHelper('foo');
equals(handlebarsEnv.helpers.foo, undefined);
});
shouldCompileTo(
"{{test_helper}} {{#if cruel}}Goodbye {{cruel}} {{world}}!{{/if}}",
[{cruel: "cruel"}],
"found it! Goodbye cruel world!!");
it('allows multiple globals', function() {
var helpers = handlebarsEnv.helpers;
handlebarsEnv.helpers = {};
handlebarsEnv.registerHelper({
'if': helpers['if'],
world: function() { return "world!"; },
test_helper: function() { return 'found it!'; }
});
shouldCompileTo(
"{{test_helper}} {{#if cruel}}Goodbye {{cruel}} {{world}}!{{/if}}",
[{cruel: "cruel"}],
"found it! Goodbye cruel world!!");
});
it('fails with multiple and args', function() {
shouldThrow(function() {
handlebarsEnv.registerHelper({
world: function() { return "world!"; },
test_helper: function() { return 'found it!'; }
}, {});
}, Error, 'Arg not supported with multiple helpers');
});
});
it("decimal number literals work", function() {
var string = 'Message: {{hello -1.2 1.2}}';
var hash = {};
var helpers = {hello: function(times, times2) {
if(typeof times !== 'number') { times = "NaN"; }
if(typeof times2 !== 'number') { times2 = "NaN"; }
return "Hello " + times + " " + times2 + " times";
}};
shouldCompileTo(string, [hash, helpers], "Message: Hello -1.2 1.2 times", "template with a negative integer literal");
});
it("negative number literals work", function() {
@@ -212,10 +284,10 @@ describe('helpers', function() {
});
it("using a quote in the middle of a parameter raises an error", function() {
(function() {
var string = 'Message: {{hello wo"rld"}}';
var string = 'Message: {{hello wo"rld"}}';
shouldThrow(function() {
CompilerContext.compile(string);
}).should.throw(Error);
}, Error);
});
it("escaping a String is possible", function(){
@@ -260,6 +332,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}}');
@@ -351,10 +424,10 @@ describe('helpers', function() {
describe("helperMissing", function() {
it("if a context is not found, helperMissing is used", function() {
(function() {
shouldThrow(function() {
var template = CompilerContext.compile("{{hello}} {{link_to world}}");
template({});
}).should.throw(/Missing helper: 'link_to'/);
}, undefined, /Missing helper: 'link_to'/);
});
it("if a context is not found, custom helperMissing is used", function() {
@@ -362,15 +435,30 @@ describe('helpers', function() {
var context = { hello: "Hello", world: "world" };
var helpers = {
helperMissing: function(helper, context) {
if(helper === "link_to") {
return new Handlebars.SafeString("<a>" + context + "</a>");
helperMissing: function(mesg, options) {
if(options.name === "link_to") {
return new Handlebars.SafeString("<a>" + mesg + "</a>");
}
}
};
shouldCompileTo(string, [context, helpers], "Hello <a>world</a>");
});
it("if a value is not found, custom helperMissing is used", function() {
var string = "{{hello}} {{link_to}}";
var context = { hello: "Hello", world: "world" };
var helpers = {
helperMissing: function(options) {
if(options.name === "link_to") {
return new Handlebars.SafeString("<a>winning</a>");
}
}
};
shouldCompileTo(string, [context, helpers], "Hello <a>winning</a>");
});
});
describe("knownHelpers", function() {
@@ -417,9 +505,9 @@ describe('helpers', function() {
equal(result, "bar", "'bar' should === '" + result);
});
it("Unknown helper call in knownHelpers only mode should throw", function() {
(function() {
shouldThrow(function() {
CompilerContext.compile("{{typeof hello}}", {knownHelpersOnly: true});
}).should.throw(Error);
}, Error);
});
});
@@ -436,6 +524,50 @@ describe('helpers', function() {
});
});
describe('name field', function() {
var context = {};
var helpers = {
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;
}
};
it('should include in ambiguous mustache calls', function() {
shouldCompileTo('{{helper}}', [context, helpers], 'ran: helper');
});
it('should include in helper mustache calls', function() {
shouldCompileTo('{{helper 1}}', [context, helpers], 'ran: helper');
});
it('should include in ambiguous block calls', function() {
shouldCompileTo('{{#helper}}{{/helper}}', [context, helpers], 'ran: helper');
});
it('should include in simple block calls', function() {
shouldCompileTo('{{#./helper}}{{/./helper}}', [context, helpers], 'missing: ./helper');
});
it('should include in helper block calls', function() {
shouldCompileTo('{{#helper 1}}{{/helper}}', [context, helpers], 'ran: helper');
});
it('should include in known helper calls', function() {
var template = CompilerContext.compile("{{helper}}", {knownHelpers: {'helper': true}, knownHelpersOnly: true});
equal(template({}, {helpers: helpers}), 'ran: helper');
});
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() {
it("helpers take precedence over same-named context properties", function() {
var template = CompilerContext.compile("{{goodbye}} {{cruel world}}");
@@ -491,7 +623,7 @@ describe('helpers', function() {
cruel: function(world) {
return "cruel " + world.toUpperCase();
},
}
};
var context = {
@@ -513,7 +645,7 @@ describe('helpers', function() {
cruel: function(world) {
return "cruel " + world.toUpperCase();
},
}
};
var context = {
@@ -525,4 +657,64 @@ describe('helpers', function() {
equals(result, "GOODBYE cruel WORLD goodbye", "Helper executed");
});
});
describe('block params', function() {
it('should take presedence over context values', function() {
var hash = {value: 'foo'};
var helpers = {
goodbyes: function(options) {
equals(options.fn.blockParams, 1);
return options.fn({value: 'bar'}, {blockParams: [1, 2]});
}
};
shouldCompileTo('{{#goodbyes as |value|}}{{value}}{{/goodbyes}}{{value}}', [hash, helpers], '1foo');
});
it('should take presedence over helper values', function() {
var hash = {};
var helpers = {
value: function() {
return 'foo';
},
goodbyes: function(options) {
equals(options.fn.blockParams, 1);
return options.fn({}, {blockParams: [1, 2]});
}
};
shouldCompileTo('{{#goodbyes as |value|}}{{value}}{{/goodbyes}}{{value}}', [hash, helpers], '1foo');
});
it('should not take presedence over pathed values', function() {
var hash = {value: 'bar'};
var helpers = {
value: function() {
return 'foo';
},
goodbyes: function(options) {
equals(options.fn.blockParams, 1);
return options.fn(this, {blockParams: [1, 2]});
}
};
shouldCompileTo('{{#goodbyes as |value|}}{{./value}}{{/goodbyes}}{{value}}', [hash, helpers], 'barfoo');
});
it('should take presednece over parent block params', function() {
var hash = {value: 'foo'},
value = 1;
var helpers = {
goodbyes: function(options) {
return options.fn({value: 'bar'}, {blockParams: options.fn.blockParams === 1 ? [value++, value++] : undefined});
}
};
shouldCompileTo('{{#goodbyes as |value|}}{{#goodbyes}}{{value}}{{#goodbyes as |value|}}{{value}}{{/goodbyes}}{{/goodbyes}}{{/goodbyes}}{{value}}', [hash, helpers], '13foo');
});
it('should allow block params on chained helpers', function() {
var hash = {value: 'foo'};
var helpers = {
goodbyes: function(options) {
equals(options.fn.blockParams, 1);
return options.fn({value: 'bar'}, {blockParams: [1, 2]});
}
};
shouldCompileTo('{{#if bar}}{{else goodbyes as |value|}}{{value}}{{/if}}{{value}}', [hash, helpers], '1foo');
});
});
});
+95
View File
@@ -0,0 +1,95 @@
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/node_modules/mocha/mocha.css" />
<style>
.headless .suite > h1,
.headless .test.pass {
display: none;
}
</style>
<script>
// Show only errors in "headless", non-interactive mode.
if (/headless=true/.test(location.href)) {
document.documentElement.className = 'headless';
}
</script>
<script src="/node_modules/mocha/mocha.js"></script>
<script>
mocha.setup('bdd');
</script>
<script src="/dist/handlebars.js"></script>
<script src="/spec/env/json2.js"></script>
<script src="/spec/env/common.js"></script>
<script>
var CompilerContext = {
compile: function(template, options) {
var templateSpec = handlebarsEnv.precompile(template, options);
return handlebarsEnv.template(safeEval(templateSpec));
},
compileWithPartial: function(template, options) {
return handlebarsEnv.compile(template, options);
}
};
function safeEval(templateSpec) {
try {
var ret;
eval('ret = ' + templateSpec);
return ret;
} catch (err) {
console.error(templateSpec);
throw err;
}
}
</script>
<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();
}
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>
<body>
<div id="mocha"></div>
</body>
</html>
+77
View File
@@ -0,0 +1,77 @@
/*global Handlebars, beforeEach, handlebarsEnv, shouldCompileTo */
describe('javascript-compiler api', function() {
if (!Handlebars.JavaScriptCompiler) {
return;
}
describe('#nameLookup', function() {
var $superName;
beforeEach(function() {
$superName = handlebarsEnv.JavaScriptCompiler.prototype.nameLookup;
});
afterEach(function() {
handlebarsEnv.JavaScriptCompiler.prototype.nameLookup = $superName;
});
it('should allow override', function() {
handlebarsEnv.JavaScriptCompiler.prototype.nameLookup = function(parent, name) {
return parent + '.bar_' + name;
};
shouldCompileTo("{{foo}}", { bar_foo: "food" }, "food");
});
// Tests nameLookup dot vs. bracket behavior. Bracket is required in certain cases
// to avoid errors in older browsers.
it('should handle reserved words', function() {
shouldCompileTo("{{foo}} {{~null~}}", { foo: "food" }, "food");
});
});
describe('#compilerInfo', function() {
var $superCheck, $superInfo;
beforeEach(function() {
$superCheck = handlebarsEnv.VM.checkRevision;
$superInfo = handlebarsEnv.JavaScriptCompiler.prototype.compilerInfo;
});
afterEach(function() {
handlebarsEnv.VM.checkRevision = $superCheck;
handlebarsEnv.JavaScriptCompiler.prototype.compilerInfo = $superInfo;
});
it('should allow compilerInfo override', function() {
handlebarsEnv.JavaScriptCompiler.prototype.compilerInfo = function() {
return 'crazy';
};
handlebarsEnv.VM.checkRevision = function(compilerInfo) {
if (compilerInfo !== 'crazy') {
throw new Error('It didn\'t work');
}
};
shouldCompileTo("{{foo}} ", { foo: "food" }, "food ");
});
});
describe('buffer', function() {
var $superAppend, $superCreate;
beforeEach(function() {
handlebarsEnv.JavaScriptCompiler.prototype.forceBuffer = true;
$superAppend = handlebarsEnv.JavaScriptCompiler.prototype.appendToBuffer;
$superCreate = handlebarsEnv.JavaScriptCompiler.prototype.initializeBuffer;
});
afterEach(function() {
handlebarsEnv.JavaScriptCompiler.prototype.forceBuffer = false;
handlebarsEnv.JavaScriptCompiler.prototype.appendToBuffer = $superAppend;
handlebarsEnv.JavaScriptCompiler.prototype.initializeBuffer = $superCreate;
});
it('should allow init buffer override', function() {
handlebarsEnv.JavaScriptCompiler.prototype.initializeBuffer = function() {
return this.quotedString('foo_');
};
shouldCompileTo("{{foo}} ", { foo: "food" }, "foo_food ");
});
it('should allow append buffer override', function() {
handlebarsEnv.JavaScriptCompiler.prototype.appendToBuffer = function(string) {
return $superAppend.call(this, [string, ' + "_foo"']);
};
shouldCompileTo("{{foo}}", { foo: "food" }, "food_foo");
});
});
});
Submodule
+1
Submodule spec/mustache added at 72233f3ffd
+113 -59
View File
@@ -1,3 +1,4 @@
/*global Handlebars, shouldThrow */
describe('parser', function() {
if (!Handlebars.print) {
return;
@@ -9,165 +10,218 @@ describe('parser', function() {
}
it('parses simple mustaches', function() {
ast_for('{{foo}}').should.equal("{{ ID:foo [] }}\n");
ast_for('{{foo?}}').should.equal("{{ ID:foo? [] }}\n");
ast_for('{{foo_}}').should.equal("{{ ID:foo_ [] }}\n");
ast_for('{{foo-}}').should.equal("{{ ID:foo- [] }}\n");
ast_for('{{foo:}}').should.equal("{{ ID:foo: [] }}\n");
equals(ast_for('{{123}}'), "{{ NUMBER{123} [] }}\n");
equals(ast_for('{{"foo"}}'), '{{ "foo" [] }}\n');
equals(ast_for('{{false}}'), '{{ BOOLEAN{false} [] }}\n');
equals(ast_for('{{true}}'), '{{ BOOLEAN{true} [] }}\n');
equals(ast_for('{{foo}}'), "{{ PATH:foo [] }}\n");
equals(ast_for('{{foo?}}'), "{{ PATH:foo? [] }}\n");
equals(ast_for('{{foo_}}'), "{{ PATH:foo_ [] }}\n");
equals(ast_for('{{foo-}}'), "{{ PATH:foo- [] }}\n");
equals(ast_for('{{foo:}}'), "{{ PATH:foo: [] }}\n");
});
it('parses simple mustaches with data', function() {
ast_for("{{@foo}}").should.equal("{{ @ID:foo [] }}\n");
equals(ast_for("{{@foo}}"), "{{ @PATH:foo [] }}\n");
});
it('parses simple mustaches with data paths', function() {
equals(ast_for("{{@../foo}}"), "{{ @PATH:foo [] }}\n");
});
it('parses mustaches with paths', function() {
ast_for("{{foo/bar}}").should.equal("{{ PATH:foo/bar [] }}\n");
equals(ast_for("{{foo/bar}}"), "{{ PATH:foo/bar [] }}\n");
});
it('parses mustaches with this/foo', function() {
ast_for("{{this/foo}}").should.equal("{{ ID:foo [] }}\n");
equals(ast_for("{{this/foo}}"), "{{ PATH:foo [] }}\n");
});
it('parses mustaches with - in a path', function() {
ast_for("{{foo-bar}}").should.equal("{{ ID:foo-bar [] }}\n");
equals(ast_for("{{foo-bar}}"), "{{ PATH:foo-bar [] }}\n");
});
it('parses mustaches with parameters', function() {
ast_for("{{foo bar}}").should.equal("{{ ID:foo [ID:bar] }}\n");
equals(ast_for("{{foo bar}}"), "{{ PATH:foo [PATH:bar] }}\n");
});
it('parses mustaches with string parameters', function() {
ast_for("{{foo bar \"baz\" }}").should.equal('{{ ID:foo [ID:bar, "baz"] }}\n');
equals(ast_for("{{foo bar \"baz\" }}"), '{{ PATH:foo [PATH:bar, "baz"] }}\n');
});
it('parses mustaches with INTEGER parameters', function() {
ast_for("{{foo 1}}").should.equal("{{ ID:foo [INTEGER{1}] }}\n");
it('parses mustaches with NUMBER parameters', function() {
equals(ast_for("{{foo 1}}"), "{{ PATH:foo [NUMBER{1}] }}\n");
});
it('parses mustaches with BOOLEAN parameters', function() {
ast_for("{{foo true}}").should.equal("{{ ID:foo [BOOLEAN{true}] }}\n");
ast_for("{{foo false}}").should.equal("{{ ID:foo [BOOLEAN{false}] }}\n");
equals(ast_for("{{foo true}}"), "{{ PATH:foo [BOOLEAN{true}] }}\n");
equals(ast_for("{{foo false}}"), "{{ PATH:foo [BOOLEAN{false}] }}\n");
});
it('parses mutaches with DATA parameters', function() {
ast_for("{{foo @bar}}").should.equal("{{ ID:foo [@ID:bar] }}\n");
equals(ast_for("{{foo @bar}}"), "{{ PATH:foo [@PATH:bar] }}\n");
});
it('parses mustaches with hash arguments', function() {
ast_for("{{foo bar=baz}}").should.equal("{{ ID:foo [] HASH{bar=ID:baz} }}\n");
ast_for("{{foo bar=1}}").should.equal("{{ ID:foo [] HASH{bar=INTEGER{1}} }}\n");
ast_for("{{foo bar=true}}").should.equal("{{ ID:foo [] HASH{bar=BOOLEAN{true}} }}\n");
ast_for("{{foo bar=false}}").should.equal("{{ ID:foo [] HASH{bar=BOOLEAN{false}} }}\n");
ast_for("{{foo bar=@baz}}").should.equal("{{ ID:foo [] HASH{bar=@ID:baz} }}\n");
equals(ast_for("{{foo bar=baz}}"), "{{ PATH:foo [] HASH{bar=PATH:baz} }}\n");
equals(ast_for("{{foo bar=1}}"), "{{ PATH:foo [] HASH{bar=NUMBER{1}} }}\n");
equals(ast_for("{{foo bar=true}}"), "{{ PATH:foo [] HASH{bar=BOOLEAN{true}} }}\n");
equals(ast_for("{{foo bar=false}}"), "{{ PATH:foo [] HASH{bar=BOOLEAN{false}} }}\n");
equals(ast_for("{{foo bar=@baz}}"), "{{ PATH:foo [] HASH{bar=@PATH:baz} }}\n");
ast_for("{{foo bar=baz bat=bam}}").should.equal("{{ ID:foo [] HASH{bar=ID:baz, bat=ID:bam} }}\n");
ast_for("{{foo bar=baz bat=\"bam\"}}").should.equal('{{ ID:foo [] HASH{bar=ID:baz, bat="bam"} }}\n');
equals(ast_for("{{foo bar=baz bat=bam}}"), "{{ PATH:foo [] HASH{bar=PATH:baz, bat=PATH:bam} }}\n");
equals(ast_for("{{foo bar=baz bat=\"bam\"}}"), '{{ PATH:foo [] HASH{bar=PATH:baz, bat="bam"} }}\n');
ast_for("{{foo bat='bam'}}").should.equal('{{ ID:foo [] HASH{bat="bam"} }}\n');
equals(ast_for("{{foo bat='bam'}}"), '{{ PATH:foo [] HASH{bat="bam"} }}\n');
ast_for("{{foo omg bar=baz bat=\"bam\"}}").should.equal('{{ ID:foo [ID:omg] HASH{bar=ID:baz, bat="bam"} }}\n');
ast_for("{{foo omg bar=baz bat=\"bam\" baz=1}}").should.equal('{{ ID:foo [ID:omg] HASH{bar=ID:baz, bat="bam", baz=INTEGER{1}} }}\n');
ast_for("{{foo omg bar=baz bat=\"bam\" baz=true}}").should.equal('{{ ID:foo [ID:omg] HASH{bar=ID:baz, bat="bam", baz=BOOLEAN{true}} }}\n');
ast_for("{{foo omg bar=baz bat=\"bam\" baz=false}}").should.equal('{{ ID:foo [ID:omg] HASH{bar=ID:baz, bat="bam", baz=BOOLEAN{false}} }}\n');
equals(ast_for("{{foo omg bar=baz bat=\"bam\"}}"), '{{ PATH:foo [PATH:omg] HASH{bar=PATH:baz, bat="bam"} }}\n');
equals(ast_for("{{foo omg bar=baz bat=\"bam\" baz=1}}"), '{{ PATH:foo [PATH:omg] HASH{bar=PATH:baz, bat="bam", baz=NUMBER{1}} }}\n');
equals(ast_for("{{foo omg bar=baz bat=\"bam\" baz=true}}"), '{{ PATH:foo [PATH:omg] HASH{bar=PATH:baz, bat="bam", baz=BOOLEAN{true}} }}\n');
equals(ast_for("{{foo omg bar=baz bat=\"bam\" baz=false}}"), '{{ PATH:foo [PATH:omg] HASH{bar=PATH:baz, bat="bam", baz=BOOLEAN{false}} }}\n');
});
it('parses contents followed by a mustache', function() {
ast_for("foo bar {{baz}}").should.equal("CONTENT[ \'foo bar \' ]\n{{ ID:baz [] }}\n");
equals(ast_for("foo bar {{baz}}"), "CONTENT[ \'foo bar \' ]\n{{ PATH:baz [] }}\n");
});
it('parses a partial', function() {
ast_for("{{> foo }}").should.equal("{{> PARTIAL:foo }}\n");
equals(ast_for("{{> foo }}"), "{{> PARTIAL:foo }}\n");
equals(ast_for("{{> 'foo' }}"), "{{> PARTIAL:foo }}\n");
equals(ast_for("{{> 1 }}"), "{{> PARTIAL:1 }}\n");
});
it('parses a partial with context', function() {
ast_for("{{> foo bar}}").should.equal("{{> PARTIAL:foo ID:bar }}\n");
equals(ast_for("{{> foo bar}}"), "{{> PARTIAL:foo PATH:bar }}\n");
});
it('parses a partial with hash', function() {
equals(ast_for("{{> foo bar=bat}}"), "{{> PARTIAL:foo HASH{bar=PATH:bat} }}\n");
});
it('parses a partial with context and hash', function() {
equals(ast_for("{{> foo bar bat=baz}}"), "{{> PARTIAL:foo PATH:bar HASH{bat=PATH:baz} }}\n");
});
it('parses a partial with a complex name', function() {
ast_for("{{> shared/partial?.bar}}").should.equal("{{> PARTIAL:shared/partial?.bar }}\n");
equals(ast_for("{{> shared/partial?.bar}}"), "{{> PARTIAL:shared/partial?.bar }}\n");
});
it('parses a comment', function() {
ast_for("{{! this is a comment }}").should.equal("{{! ' this is a comment ' }}\n");
equals(ast_for("{{! this is a comment }}"), "{{! ' this is a comment ' }}\n");
});
it('parses a multi-line comment', function() {
ast_for("{{!\nthis is a multi-line comment\n}}").should.equal("{{! \'\nthis is a multi-line comment\n\' }}\n");
equals(ast_for("{{!\nthis is a multi-line comment\n}}"), "{{! \'\nthis is a multi-line comment\n\' }}\n");
});
it('parses an inverse section', function() {
ast_for("{{#foo}} bar {{^}} baz {{/foo}}").should.equal("BLOCK:\n {{ ID:foo [] }}\n PROGRAM:\n CONTENT[ ' bar ' ]\n {{^}}\n CONTENT[ ' baz ' ]\n");
equals(ast_for("{{#foo}} bar {{^}} baz {{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n CONTENT[ ' bar ' ]\n {{^}}\n CONTENT[ ' baz ' ]\n");
});
it('parses an inverse (else-style) section', function() {
ast_for("{{#foo}} bar {{else}} baz {{/foo}}").should.equal("BLOCK:\n {{ ID:foo [] }}\n PROGRAM:\n CONTENT[ ' bar ' ]\n {{^}}\n CONTENT[ ' baz ' ]\n");
equals(ast_for("{{#foo}} bar {{else}} baz {{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n CONTENT[ ' bar ' ]\n {{^}}\n CONTENT[ ' baz ' ]\n");
});
it('parses multiple inverse sections', function() {
equals(ast_for("{{#foo}} bar {{else if bar}}{{else}} baz {{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n CONTENT[ ' bar ' ]\n {{^}}\n BLOCK:\n PATH:if [PATH:bar]\n PROGRAM:\n {{^}}\n CONTENT[ ' baz ' ]\n");
});
it('parses empty blocks', function() {
ast_for("{{#foo}}{{/foo}}").should.equal("BLOCK:\n {{ ID:foo [] }}\n PROGRAM:\n");
equals(ast_for("{{#foo}}{{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n");
});
it('parses empty blocks with empty inverse section', function() {
ast_for("{{#foo}}{{^}}{{/foo}}").should.equal("BLOCK:\n {{ ID:foo [] }}\n PROGRAM:\n");
equals(ast_for("{{#foo}}{{^}}{{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n {{^}}\n");
});
it('parses empty blocks with empty inverse (else-style) section', function() {
ast_for("{{#foo}}{{else}}{{/foo}}").should.equal("BLOCK:\n {{ ID:foo [] }}\n PROGRAM:\n");
equals(ast_for("{{#foo}}{{else}}{{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n {{^}}\n");
});
it('parses non-empty blocks with empty inverse section', function() {
ast_for("{{#foo}} bar {{^}}{{/foo}}").should.equal("BLOCK:\n {{ ID:foo [] }}\n PROGRAM:\n CONTENT[ ' bar ' ]\n {{^}}\n");
equals(ast_for("{{#foo}} bar {{^}}{{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n CONTENT[ ' bar ' ]\n {{^}}\n");
});
it('parses non-empty blocks with empty inverse (else-style) section', function() {
ast_for("{{#foo}} bar {{else}}{{/foo}}").should.equal("BLOCK:\n {{ ID:foo [] }}\n PROGRAM:\n CONTENT[ ' bar ' ]\n {{^}}\n");
equals(ast_for("{{#foo}} bar {{else}}{{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n CONTENT[ ' bar ' ]\n {{^}}\n");
});
it('parses empty blocks with non-empty inverse section', function() {
ast_for("{{#foo}}{{^}} bar {{/foo}}").should.equal("BLOCK:\n {{ ID:foo [] }}\n PROGRAM:\n {{^}}\n CONTENT[ ' bar ' ]\n");
equals(ast_for("{{#foo}}{{^}} bar {{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n {{^}}\n CONTENT[ ' bar ' ]\n");
});
it('parses empty blocks with non-empty inverse (else-style) section', function() {
ast_for("{{#foo}}{{else}} bar {{/foo}}").should.equal("BLOCK:\n {{ ID:foo [] }}\n PROGRAM:\n {{^}}\n CONTENT[ ' bar ' ]\n");
equals(ast_for("{{#foo}}{{else}} bar {{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n {{^}}\n CONTENT[ ' bar ' ]\n");
});
it('parses a standalone inverse section', function() {
ast_for("{{^foo}}bar{{/foo}}").should.equal("BLOCK:\n {{ ID:foo [] }}\n {{^}}\n CONTENT[ 'bar' ]\n");
equals(ast_for("{{^foo}}bar{{/foo}}"), "BLOCK:\n PATH:foo []\n {{^}}\n CONTENT[ 'bar' ]\n");
});
it('throws on old inverse section', function() {
shouldThrow(function() {
ast_for("{{else foo}}bar{{/foo}}");
}, Error);
});
it('parses block with block params', function() {
equals(ast_for("{{#foo as |bar baz|}}content{{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n BLOCK PARAMS: [ bar baz ]\n CONTENT[ 'content' ]\n");
});
it('parses inverse block with block params', function() {
equals(ast_for("{{^foo as |bar baz|}}content{{/foo}}"), "BLOCK:\n PATH:foo []\n {{^}}\n BLOCK PARAMS: [ bar baz ]\n CONTENT[ 'content' ]\n");
});
it('parses chained inverse block with block params', function() {
equals(ast_for("{{#foo}}{{else foo as |bar baz|}}content{{/foo}}"), "BLOCK:\n PATH:foo []\n PROGRAM:\n {{^}}\n BLOCK:\n PATH:foo []\n PROGRAM:\n BLOCK PARAMS: [ bar baz ]\n CONTENT[ 'content' ]\n");
});
it("raises if there's a Parse error", function() {
(function() {
shouldThrow(function() {
ast_for("foo{{^}}bar");
}).should.throw(/Parse error on line 1/);
(function() {
}, Error, /Parse error on line 1/);
shouldThrow(function() {
ast_for("{{foo}");
}).should.throw(/Parse error on line 1/);
(function() {
}, Error, /Parse error on line 1/);
shouldThrow(function() {
ast_for("{{foo &}}");
}).should.throw(/Parse error on line 1/);
(function() {
}, Error, /Parse error on line 1/);
shouldThrow(function() {
ast_for("{{#goodbyes}}{{/hellos}}");
}).should.throw(/goodbyes doesn't match hellos/);
}, Error, /goodbyes doesn't match hellos/);
shouldThrow(function() {
ast_for("{{{{goodbyes}}}} {{{{/hellos}}}}");
}, Error, /goodbyes doesn't match hellos/);
});
it('should handle invalid paths', function() {
shouldThrow(function() {
ast_for("{{foo/../bar}}");
}, Error, /Invalid path: foo\/\.\. - 1:2/);
shouldThrow(function() {
ast_for("{{foo/./bar}}");
}, Error, /Invalid path: foo\/\. - 1:2/);
shouldThrow(function() {
ast_for("{{foo/this/bar}}");
}, Error, /Invalid path: foo\/this - 1:2/);
});
it('knows how to report the correct line number in errors', function() {
(function() {
shouldThrow(function() {
ast_for("hello\nmy\n{{foo}");
}).should.throw(/Parse error on line 3/);
(function() {
}, Error, /Parse error on line 3/);
shouldThrow(function() {
ast_for("hello\n\nmy\n\n{{foo}");
}).should.throw(/Parse error on line 5/);
}, Error, /Parse error on line 5/);
});
it('knows how to report the correct line number in errors when the first character is a newline', function() {
(function() {
shouldThrow(function() {
ast_for("\n\nhello\n\nmy\n\n{{foo}");
}).should.throw(/Parse error on line 7/);
}, Error, /Parse error on line 7/);
});
describe('externally compiled AST', function() {
it('can pass through an already-compiled AST', function() {
ast_for(new Handlebars.AST.ProgramNode([ new Handlebars.AST.ContentNode("Hello")])).should.equal("CONTENT[ \'Hello\' ]\n");
equals(ast_for(new Handlebars.AST.Program([new Handlebars.AST.ContentStatement("Hello")], null)), "CONTENT[ \'Hello\' ]\n");
});
});
});
+139 -17
View File
@@ -1,11 +1,37 @@
/*global CompilerContext, shouldCompileTo, shouldCompileToWithPartials */
/*global CompilerContext, Handlebars, handlebarsEnv, shouldCompileTo, shouldCompileToWithPartials, shouldThrow */
describe('partials', function() {
it("basic partials", function() {
var string = "Dudes: {{#dudes}}{{> dude}}{{/dudes}}";
var partial = "{{name}} ({{url}}) ";
var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]};
shouldCompileToWithPartials(string, [hash, {}, {dude: partial}], true, "Dudes: Yehuda (http://yehuda) Alan (http://alan) ",
"Basic partials output based on current context.");
it('basic partials', function() {
var string = 'Dudes: {{#dudes}}{{> dude}}{{/dudes}}';
var partial = '{{name}} ({{url}}) ';
var hash = {dudes: [{name: 'Yehuda', url: 'http://yehuda'}, {name: 'Alan', url: 'http://alan'}]};
shouldCompileToWithPartials(string, [hash, {}, {dude: partial}], true, 'Dudes: Yehuda (http://yehuda) Alan (http://alan) ');
shouldCompileToWithPartials(string, [hash, {}, {dude: partial},,false], true, 'Dudes: Yehuda (http://yehuda) Alan (http://alan) ');
});
it('dynamic partials', function() {
var string = 'Dudes: {{#dudes}}{{> (partial)}}{{/dudes}}';
var partial = '{{name}} ({{url}}) ';
var hash = {dudes: [{name: 'Yehuda', url: 'http://yehuda'}, {name: 'Alan', url: 'http://alan'}]};
var helpers = {
partial: function() {
return 'dude';
}
};
shouldCompileToWithPartials(string, [hash, helpers, {dude: partial}], true, 'Dudes: Yehuda (http://yehuda) Alan (http://alan) ');
shouldCompileToWithPartials(string, [hash, helpers, {dude: partial},,false], true, 'Dudes: Yehuda (http://yehuda) Alan (http://alan) ');
});
it('failing dynamic partials', function() {
var string = 'Dudes: {{#dudes}}{{> (partial)}}{{/dudes}}';
var partial = '{{name}} ({{url}}) ';
var hash = {dudes: [{name: 'Yehuda', url: 'http://yehuda'}, {name: 'Alan', url: 'http://alan'}]};
var helpers = {
partial: function() {
return 'missing';
}
};
shouldThrow(function() {
shouldCompileToWithPartials(string, [hash, helpers, {dude: partial}], true, 'Dudes: Yehuda (http://yehuda) Alan (http://alan) ');
}, Handlebars.Exception, 'The partial missing could not be found');
});
it("partials with context", function() {
@@ -23,6 +49,20 @@ describe('partials', function() {
shouldCompileToWithPartials(string, [hash, {}, {dude: partial}], true, "Dudes: Empty");
});
it('partials with duplicate parameters', function() {
shouldThrow(function() {
CompilerContext.compile('Dudes: {{>dude dudes foo bar=baz}}');
}, Error, 'Unsupported number of partial arguments: 2 - 1:7');
});
it("partials with parameters", function() {
var string = "Dudes: {{#dudes}}{{> dude others=..}}{{/dudes}}";
var partial = "{{others.foo}}{{name}} ({{url}}) ";
var hash = {foo: 'bar', dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]};
shouldCompileToWithPartials(string, [hash, {}, {dude: partial}], true, "Dudes: barYehuda (http://yehuda) barAlan (http://alan) ",
"Basic partials output based on current context.");
});
it("partial in a partial", function() {
var string = "Dudes: {{#dudes}}{{>dude}}{{/dudes}}";
var dude = "{{name}} {{> url}} ";
@@ -32,17 +72,24 @@ describe('partials', function() {
});
it("rendering undefined partial throws an exception", function() {
(function() {
var template = CompilerContext.compile("{{> whatever}}");
template();
}).should.throw(Handlebars.Exception, 'The partial whatever could not be found');
shouldThrow(function() {
var template = CompilerContext.compile("{{> whatever}}");
template();
}, Handlebars.Exception, 'The partial whatever could not be found');
});
it("registering undefined partial throws an exception", function() {
shouldThrow(function() {
var undef;
handlebarsEnv.registerPartial('undefined_test', undef);
}, Handlebars.Exception, 'Attempting to register a partial as undefined');
});
it("rendering template partial in vm mode throws an exception", function() {
(function() {
shouldThrow(function() {
var template = CompilerContext.compile("{{> whatever}}");
template();
}).should.throw(Handlebars.Exception, 'The partial whatever could not be found');
}, Handlebars.Exception, 'The partial whatever could not be found');
});
it("rendering function partial in vm mode", function() {
@@ -56,10 +103,10 @@ describe('partials', function() {
});
it("GH-14: a partial preceding a selector", function() {
var string = "Dudes: {{>dude}} {{another_dude}}";
var dude = "{{name}}";
var hash = {name:"Jeepers", another_dude:"Creepers"};
shouldCompileToWithPartials(string, [hash, {}, {dude:dude}], true, "Dudes: Jeepers Creepers", "Regular selectors can follow a partial");
var string = "Dudes: {{>dude}} {{another_dude}}";
var dude = "{{name}}";
var hash = {name:"Jeepers", another_dude:"Creepers"};
shouldCompileToWithPartials(string, [hash, {}, {dude:dude}], true, "Dudes: Jeepers Creepers", "Regular selectors can follow a partial");
});
it("Partials with slash paths", function() {
@@ -83,6 +130,9 @@ describe('partials', function() {
var dude = "{{name}}";
var hash = {name:"Jeepers", another_dude:"Creepers"};
shouldCompileToWithPartials(string, [hash, {}, {'shared/dude':dude}], true, "Dudes: Jeepers Creepers", "Partials can use globals or passed");
handlebarsEnv.unregisterPartial('global_test');
equals(handlebarsEnv.partials.global_test, undefined);
});
it("Multiple partial registration", function() {
@@ -123,4 +173,76 @@ describe('partials', function() {
var hash = {name:"Jeepers", another_dude:"Creepers"};
shouldCompileToWithPartials(string, [hash, {}, {'+404/asdf?.bar':dude}], true, "Dudes: Jeepers", "Partials can use literal paths");
});
it('should handle empty partial', function() {
var string = "Dudes: {{#dudes}}{{> dude}}{{/dudes}}";
var partial = "";
var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]};
shouldCompileToWithPartials(string, [hash, {}, {dude: partial}], true, "Dudes: ");
});
it("throw on missing partial", function() {
var compile = handlebarsEnv.compile;
handlebarsEnv.compile = undefined;
shouldThrow(function() {
shouldCompileTo('{{> dude}}', [{}, {}, {dude: 'fail'}], '');
}, Error, /The partial dude could not be compiled/);
handlebarsEnv.compile = compile;
});
it('should pass compiler flags', function() {
if (Handlebars.compile) {
var env = Handlebars.create();
env.registerPartial('partial', '{{foo}}');
var template = env.compile('{{foo}} {{> partial}}', {noEscape: true});
equal(template({foo: '<'}), '< <');
}
});
describe('standalone partials', function() {
it("indented partials", function() {
var string = "Dudes:\n{{#dudes}}\n {{>dude}}\n{{/dudes}}";
var dude = "{{name}}\n";
var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]};
shouldCompileToWithPartials(string, [hash, {}, {dude: dude}], true,
"Dudes:\n Yehuda\n Alan\n");
});
it("nested indented partials", function() {
var string = "Dudes:\n{{#dudes}}\n {{>dude}}\n{{/dudes}}";
var dude = "{{name}}\n {{> url}}";
var url = "{{url}}!\n";
var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]};
shouldCompileToWithPartials(string, [hash, {}, {dude: dude, url: url}], true,
"Dudes:\n Yehuda\n http://yehuda!\n Alan\n http://alan!\n");
});
it("prevent nested indented partials", function() {
var string = "Dudes:\n{{#dudes}}\n {{>dude}}\n{{/dudes}}";
var dude = "{{name}}\n {{> url}}";
var url = "{{url}}!\n";
var hash = {dudes: [{name: "Yehuda", url: "http://yehuda"}, {name: "Alan", url: "http://alan"}]};
shouldCompileToWithPartials(string, [hash, {}, {dude: dude, url: url}, {preventIndent: true}], true,
"Dudes:\n Yehuda\n http://yehuda!\n Alan\n http://alan!\n");
});
});
describe('compat mode', function() {
it('partials can access parents', function() {
var string = 'Dudes: {{#dudes}}{{> dude}}{{/dudes}}';
var partial = '{{name}} ({{url}}) {{root}} ';
var hash = {root: 'yes', dudes: [{name: 'Yehuda', url: 'http://yehuda'}, {name: 'Alan', url: 'http://alan'}]};
shouldCompileToWithPartials(string, [hash, {}, {dude: partial}, true], true, 'Dudes: Yehuda (http://yehuda) yes Alan (http://alan) yes ');
});
it('partials can access parents without data', function() {
var string = 'Dudes: {{#dudes}}{{> dude}}{{/dudes}}';
var partial = '{{name}} ({{url}}) {{root}} ';
var hash = {root: 'yes', dudes: [{name: 'Yehuda', url: 'http://yehuda'}, {name: 'Alan', url: 'http://alan'}]};
shouldCompileToWithPartials(string, [hash, {}, {dude: partial}, true, false], true, 'Dudes: Yehuda (http://yehuda) yes Alan (http://alan) yes ');
});
it('partials inherit compat', function() {
var string = 'Dudes: {{> dude}}';
var partial = '{{#dudes}}{{name}} ({{url}}) {{root}} {{/dudes}}';
var hash = {root: 'yes', dudes: [{name: 'Yehuda', url: 'http://yehuda'}, {name: 'Alan', url: 'http://alan'}]};
shouldCompileToWithPartials(string, [hash, {}, {dude: partial}, true], true, 'Dudes: Yehuda (http://yehuda) yes Alan (http://alan) yes ');
});
});
});
+174
View File
@@ -0,0 +1,174 @@
/*global shouldThrow */
describe('precompiler', function() {
// NOP Under non-node environments
if (typeof process === 'undefined') {
return;
}
var Handlebars = require('../lib'),
Precompiler = require('../lib/precompiler'),
fs = require('fs'),
uglify = require('uglify-js');
var log,
logFunction,
precompile,
minify,
file,
content,
writeFileSync;
beforeEach(function() {
precompile = Handlebars.precompile;
minify = uglify.minify;
writeFileSync = fs.writeFileSync;
logFunction = console.log;
log = '';
console.log = function() {
log += Array.prototype.join.call(arguments, '');
};
fs.writeFileSync = function(_file, _content) {
file = _file;
content = _content;
};
});
afterEach(function() {
Handlebars.precompile = precompile;
uglify.minify = minify;
fs.writeFileSync = writeFileSync;
console.log = logFunction;
});
it('should output version', function() {
Precompiler.cli({templates: [], version: true});
equals(log, Handlebars.VERSION);
});
it('should throw if lacking templates', function() {
shouldThrow(function() {
Precompiler.cli({templates: []});
}, Handlebars.Exception, 'Must define at least one template or directory.');
});
it('should throw on missing template', function() {
shouldThrow(function() {
Precompiler.cli({templates: ['foo']});
}, Handlebars.Exception, 'Unable to open template file "foo"');
});
it('should throw when combining simple and minimized', function() {
shouldThrow(function() {
Precompiler.cli({templates: [__dirname], simple: true, min: true});
}, Handlebars.Exception, 'Unable to minimize simple output');
});
it('should throw when combining simple and multiple templates', function() {
shouldThrow(function() {
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars', __dirname + '/artifacts/empty.handlebars'], simple: true});
}, Handlebars.Exception, 'Unable to output multiple templates in simple mode');
});
it('should throw when combining simple and directories', function() {
shouldThrow(function() {
Precompiler.cli({templates: [__dirname], simple: true});
}, Handlebars.Exception, 'Unable to output multiple templates in simple mode');
});
it('should enumerate directories by extension', function() {
Precompiler.cli({templates: [__dirname + '/artifacts'], extension: 'hbs'});
equal(/'example_2'/.test(log), true);
log = '';
Precompiler.cli({templates: [__dirname + '/artifacts'], extension: 'handlebars'});
equal(/'empty'/.test(log), true);
equal(/'example_1'/.test(log), true);
});
it('should protect from regexp patterns', function() {
Precompiler.cli({templates: [__dirname + '/artifacts'], extension: 'hb(s'});
// Success is not throwing
});
it('should output simple templates', function() {
Handlebars.precompile = function() { return 'simple'; };
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], simple: true, extension: 'handlebars'});
equal(log, 'simple\n');
});
it('should output amd templates', function() {
Handlebars.precompile = function() { return 'amd'; };
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], amd: true, extension: 'handlebars'});
equal(/template\(amd\)/.test(log), true);
});
it('should output multiple amd', function() {
Handlebars.precompile = function() { return 'amd'; };
Precompiler.cli({templates: [__dirname + '/artifacts'], amd: true, extension: 'handlebars', namespace: 'foo'});
equal(/templates = foo = foo \|\|/.test(log), true);
equal(/return templates/.test(log), true);
equal(/template\(amd\)/.test(log), true);
});
it('should output amd partials', function() {
Handlebars.precompile = function() { return 'amd'; };
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], amd: true, partial: true, extension: 'handlebars'});
equal(/return Handlebars\.partials\['empty'\]/.test(log), true);
equal(/template\(amd\)/.test(log), true);
});
it('should output multiple amd partials', function() {
Handlebars.precompile = function() { return 'amd'; };
Precompiler.cli({templates: [__dirname + '/artifacts'], amd: true, partial: true, extension: 'handlebars'});
equal(/return Handlebars\.partials\[/.test(log), false);
equal(/template\(amd\)/.test(log), true);
});
it('should output commonjs templates', function() {
Handlebars.precompile = function() { return 'commonjs'; };
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], commonjs: true, extension: 'handlebars'});
equal(/template\(commonjs\)/.test(log), true);
});
it('should set data flag', function() {
Handlebars.precompile = function(data, options) { equal(options.data, true); return 'simple'; };
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], simple: true, extension: 'handlebars', data: true});
equal(log, 'simple\n');
});
it('should set known helpers', function() {
Handlebars.precompile = function(data, options) { equal(options.knownHelpers.foo, true); return 'simple'; };
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], simple: true, extension: 'handlebars', known: 'foo'});
equal(log, 'simple\n');
});
it('should handle different root', function() {
Handlebars.precompile = function() { return 'simple'; };
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], simple: true, extension: 'handlebars', root: 'foo/'});
equal(log, 'simple\n');
});
it('should output to file system', function() {
Handlebars.precompile = function() { return 'simple'; };
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], simple: true, extension: 'handlebars', output: 'file!'});
equal(file, 'file!');
equal(content, 'simple\n');
equal(log, '');
});
it('should handle BOM', function() {
Handlebars.precompile = function(template) { return template === 'a' ? 'simple' : 'fail'; };
Precompiler.cli({templates: [__dirname + '/artifacts/bom.handlebars'], simple: true, extension: 'handlebars', bom: true});
equal(log, 'simple\n');
});
it('should output minimized templates', function() {
Handlebars.precompile = function() { return 'amd'; };
uglify.minify = function() { return {code: 'min'}; };
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], min: true, extension: 'handlebars'});
equal(log, 'min');
});
it('should output map', function() {
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], map: 'foo.js.map', extension: 'handlebars'});
equal(file, 'foo.js.map');
equal(/sourceMappingURL=/.test(log), true);
});
it('should output map', function() {
Precompiler.cli({templates: [__dirname + '/artifacts/empty.handlebars'], min: true, map: 'foo.js.map', extension: 'handlebars'});
equal(file, 'foo.js.map');
equal(/sourceMappingURL=/.test(log), true);
});
});
+62 -16
View File
@@ -1,4 +1,4 @@
/*global CompilerContext, shouldCompileTo */
/*global CompilerContext, shouldCompileTo, shouldThrow */
describe('Regressions', function() {
it("GH-94: Cannot read property of undefined", function() {
var data = {"books":[{"title":"The origin of species","author":{"name":"Charles Darwin"}},{"title":"Lazarillo de Tormes"}]};
@@ -24,7 +24,19 @@ describe('Regressions', function() {
});
it("bug reported by @fat where lambdas weren't being properly resolved", function() {
var string = "<strong>This is a slightly more complicated {{thing}}.</strong>.\n{{! Just ignore this business. }}\nCheck this out:\n{{#hasThings}}\n<ul>\n{{#things}}\n<li class={{className}}>{{word}}</li>\n{{/things}}</ul>.\n{{/hasThings}}\n{{^hasThings}}\n\n<small>Nothing to check out...</small>\n{{/hasThings}}";
var string = '<strong>This is a slightly more complicated {{thing}}.</strong>.\n'
+ '{{! Just ignore this business. }}\n'
+ 'Check this out:\n'
+ '{{#hasThings}}\n'
+ '<ul>\n'
+ '{{#things}}\n'
+ '<li class={{className}}>{{word}}</li>\n'
+ '{{/things}}</ul>.\n'
+ '{{/hasThings}}\n'
+ '{{^hasThings}}\n'
+ '\n'
+ '<small>Nothing to check out...</small>\n'
+ '{{/hasThings}}';
var data = {
thing: function() {
return "blah";
@@ -39,7 +51,13 @@ describe('Regressions', function() {
}
};
var output = "<strong>This is a slightly more complicated blah.</strong>.\n\nCheck this out:\n\n<ul>\n\n<li class=one>@fat</li>\n\n<li class=two>@dhg</li>\n\n<li class=three>@sayrer</li>\n</ul>.\n\n";
var output = '<strong>This is a slightly more complicated blah.</strong>.\n'
+ 'Check this out:\n'
+ '<ul>\n'
+ '<li class=one>@fat</li>\n'
+ '<li class=two>@dhg</li>\n'
+ '<li class=three>@sayrer</li>\n'
+ '</ul>.\n';
shouldCompileTo(string, data, output);
});
@@ -85,12 +103,19 @@ describe('Regressions', function() {
});
it('GH-437: Matching escaping', function() {
(function() {
shouldThrow(function() {
CompilerContext.compile('{{{a}}');
}).should.throw(Error);
(function() {
}, Error);
shouldThrow(function() {
CompilerContext.compile('{{a}}}');
}).should.throw(Error);
}, Error);
});
it("GH-676: Using array in escaping mustache fails", function() {
var string = "{{arr}}";
var data = { "arr": [1,2] };
shouldCompileTo(string, data, data.arr.toString(), "it works as expected");
});
it("Mustache man page", function() {
@@ -105,15 +130,36 @@ describe('Regressions', function() {
shouldCompileTo(string, data, "Hello Chris. You have just won $10000! Well, $6000, after taxes.", "the hello world mustache example works");
});
it("Passing falsy values to Handlebars.compile throws an error", function() {
(function() {
CompilerContext.compile(null);
}).should.throw("You must pass a string or Handlebars AST to Handlebars.precompile. You passed null");
it('GH-731: zero context rendering', function() {
shouldCompileTo('{{#foo}} This is {{bar}} ~ {{/foo}}', {foo: 0, bar: 'OK'}, ' This is ~ ');
});
if (Handlebars.AST) {
it("can pass through an already-compiled AST via compile/precompile", function() {
equal(Handlebars.compile(new Handlebars.AST.ProgramNode([ new Handlebars.AST.ContentNode("Hello")]))(), 'Hello');
});
}
it('GH-820: zero pathed rendering', function() {
shouldCompileTo('{{foo.bar}}', {foo: 0}, '');
});
it('GH-837: undefined values for helpers', function() {
var helpers = {
str: function(value) { return value + ''; }
};
shouldCompileTo('{{str bar.baz}}', [{}, helpers], 'undefined');
});
it('GH-926: Depths and de-dupe', function() {
var context = {
name: 'foo',
data: [
1
],
notData: [
1
]
};
var template = CompilerContext.compile('{{#if dater}}{{#each data}}{{../name}}{{/each}}{{else}}{{#each notData}}{{../name}}{{/each}}{{/if}}');
var result = template(context);
equals(result, 'foo');
});
});
+4 -4
View File
@@ -2,22 +2,22 @@ if (typeof(require) !== 'undefined' && require.extensions[".handlebars"]) {
describe('Require', function() {
it('Load .handlebars files with require()', function() {
var template = require("./artifacts/example_1");
template.should.eql(require("./artifacts/example_1.handlebars"));
equal(template, require("./artifacts/example_1.handlebars"));
var expected = 'foo\n';
var result = template({foo: "foo"});
result.should.equal(expected);
equal(result, expected);
});
it('Load .hbs files with require()', function() {
var template = require("./artifacts/example_2");
template.should.eql(require("./artifacts/example_2.hbs"));
equal(template, require("./artifacts/example_2.hbs"));
var expected = 'Hello, World!\n';
var result = template({name: "World"});
result.should.equal(expected);
equal(result, expected);
});
});
}
+91
View File
@@ -0,0 +1,91 @@
/*globals Handlebars, shouldThrow */
describe('runtime', function() {
describe('#template', function() {
it('should throw on invalid templates', function() {
shouldThrow(function() {
Handlebars.template({});
}, Error, 'Unknown template object: object');
shouldThrow(function() {
Handlebars.template();
}, Error, 'Unknown template object: undefined');
shouldThrow(function() {
Handlebars.template('');
}, Error, 'Unknown template object: string');
});
it('should throw on version mismatch', function() {
shouldThrow(function() {
Handlebars.template({
main: true,
compiler: [Handlebars.COMPILER_REVISION + 1]
});
}, Error, /Template was precompiled with a newer version of Handlebars than the current runtime/);
shouldThrow(function() {
Handlebars.template({
main: true,
compiler: [Handlebars.COMPILER_REVISION - 1]
});
}, Error, /Template was precompiled with an older version of Handlebars than the current runtime/);
shouldThrow(function() {
Handlebars.template({
main: true
});
}, Error, /Template was precompiled with an older version of Handlebars than the current runtime/);
});
});
describe('#child', function() {
if (!Handlebars.compile) {
return;
}
it('should throw for depthed methods without depths', function() {
shouldThrow(function() {
var template = Handlebars.compile('{{#foo}}{{../bar}}{{/foo}}');
// Calling twice to hit the non-compiled case.
template._setup({});
template._setup({});
template._child(1);
}, Error, 'must pass parent depths');
});
it('should throw for block param methods without params', function() {
shouldThrow(function() {
var template = Handlebars.compile('{{#foo as |foo|}}{{foo}}{{/foo}}');
// Calling twice to hit the non-compiled case.
template._setup({});
template._setup({});
template._child(1);
}, Error, 'must pass block params');
});
it('should expose child template', function() {
var template = Handlebars.compile('{{#foo}}bar{{/foo}}');
// Calling twice to hit the non-compiled case.
equal(template._child(1)(), 'bar');
equal(template._child(1)(), 'bar');
});
it('should render depthed content', function() {
var template = Handlebars.compile('{{#foo}}{{../bar}}{{/foo}}');
// Calling twice to hit the non-compiled case.
equal(template._child(1, undefined, [], [{bar: 'baz'}])(), 'baz');
});
});
describe('#noConflict', function() {
if (!CompilerContext.browser) {
return;
}
it('should reset on no conflict', function() {
var reset = Handlebars;
Handlebars.noConflict();
equal(Handlebars, 'no-conflict');
Handlebars = 'really, none';
reset.noConflict();
equal(Handlebars, 'really, none');
Handlebars = reset;
});
});
});
+49
View File
@@ -0,0 +1,49 @@
/*global CompilerContext, Handlebars */
try {
var SourceMap = require('source-map'),
SourceMapConsumer = SourceMap.SourceMapConsumer;
} catch (err) {
/* NOP for in browser */
}
describe('source-map', function() {
if (!Handlebars.precompile || !SourceMap) {
return;
}
it('should safely include source map info', function() {
var template = Handlebars.precompile('{{hello}}', {destName: 'dest.js', srcName: 'src.hbs'});
equal(!!template.code, true);
equal(!!template.map, !CompilerContext.browser);
});
it('should map source properly', function() {
var source = ' b{{hello}} \n {{bar}}a {{#block arg hash=(subex 1 subval)}}{{/block}}',
template = Handlebars.precompile(source, {destName: 'dest.js', srcName: 'src.hbs'});
if (template.map) {
var consumer = new SourceMapConsumer(template.map),
lines = template.code.split('\n'),
srcLines = source.split('\n'),
generated = grepLine('" b"', lines),
source = grepLine(' b', srcLines);
var mapped = consumer.originalPositionFor(generated);
equal(mapped.line, source.line);
equal(mapped.column, source.column);
}
});
});
function grepLine(token, lines) {
for (var i = 0; i < lines.length; i++) {
var column = lines[i].indexOf(token);
if (column >= 0) {
return {
line: i+1,
column: column
};
}
}
}
+49
View File
@@ -0,0 +1,49 @@
describe('spec', function() {
// NOP Under non-node environments
if (typeof process === 'undefined') {
return;
}
var _ = require('underscore'),
Handlebars = require('../lib'),
fs = require('fs');
var specDir =__dirname + '/mustache/specs/';
var specs = _.filter(fs.readdirSync(specDir), function(name) {
return /.*\.json$/.test(name);
});
_.each(specs, function(name) {
var spec = require(specDir + name);
_.each(spec.tests, function(test) {
// Our lambda implementation knowingly deviates from the optional Mustace lambda spec
// We also do not support alternative delimeters
if (name === '~lambdas.json'
// We also choose to throw if paritals are not found
|| (name === 'partials.json' && test.name === 'Failed Lookup')
// We nest the entire response from partials, not just the literals
|| (name === 'partials.json' && test.name === 'Standalone Indentation')
|| /\{\{\=/.test(test.template)
|| _.any(test.partials, function(partial) { return /\{\{\=/.test(partial); })) {
it.skip(name + ' - ' + test.name);
return;
}
var data = _.clone(test.data);
if (data.lambda) {
// Blergh
data.lambda = eval('(' + data.lambda.js + ')');
}
it(name + ' - ' + test.name, function() {
if (test.partials) {
shouldCompileToWithPartials(test.template, [data, {}, test.partials, true], true, test.expected, test.desc + ' "' + test.template + '"');
} else {
shouldCompileTo(test.template, [data, {}, {}, true], test.expected, test.desc + ' "' + test.template + '"');
}
});
});
});
});
+124
View File
@@ -0,0 +1,124 @@
/*global CompilerContext, Handlebars, shouldThrow */
var Exception = Handlebars.Exception;
describe('strict', function() {
describe('strict mode', function() {
it('should error on missing property lookup', function() {
shouldThrow(function() {
var template = CompilerContext.compile('{{hello}}', {strict: true});
template({});
}, Exception, /"hello" not defined in/);
});
it('should error on missing child', function() {
var template = CompilerContext.compile('{{hello.bar}}', {strict: true});
equals(template({hello: {bar: 'foo'}}), 'foo');
shouldThrow(function() {
template({hello: {}});
}, Exception, /"bar" not defined in/);
});
it('should handle explicit undefined', function() {
var template = CompilerContext.compile('{{hello.bar}}', {strict: true});
equals(template({hello: {bar: undefined}}), '');
});
it('should error on missing property lookup in known helpers mode', function() {
shouldThrow(function() {
var template = CompilerContext.compile('{{hello}}', {strict: true, knownHelpersOnly: true});
template({});
}, Exception, /"hello" not defined in/);
});
it('should error on missing context', function() {
shouldThrow(function() {
var template = CompilerContext.compile('{{hello}}', {strict: true});
template();
}, Error);
});
it('should error on missing data lookup', function() {
var template = CompilerContext.compile('{{@hello}}', {strict: true});
equals(template(undefined, {data: {hello: 'foo'}}), 'foo');
shouldThrow(function() {
template();
}, Error);
});
it('should not run helperMissing for helper calls', function() {
shouldThrow(function() {
var template = CompilerContext.compile('{{hello foo}}', {strict: true});
template({foo: true});
}, Exception, /"hello" not defined in/);
shouldThrow(function() {
var template = CompilerContext.compile('{{#hello foo}}{{/hello}}', {strict: true});
template({foo: true});
}, Exception, /"hello" not defined in/);
});
it('should throw on ambiguous blocks', function() {
shouldThrow(function() {
var template = CompilerContext.compile('{{#hello}}{{/hello}}', {strict: true});
template({});
}, Exception, /"hello" not defined in/);
shouldThrow(function() {
var template = CompilerContext.compile('{{^hello}}{{/hello}}', {strict: true});
template({});
}, Exception, /"hello" not defined in/);
shouldThrow(function() {
var template = CompilerContext.compile('{{#hello.bar}}{{/hello.bar}}', {strict: true});
template({hello: {}});
}, Exception, /"bar" not defined in/);
});
});
describe('assume objects', function() {
it('should ignore missing property', function() {
var template = CompilerContext.compile('{{hello}}', {assumeObjects: true});
equal(template({}), '');
});
it('should ignore missing child', function() {
var template = CompilerContext.compile('{{hello.bar}}', {assumeObjects: true});
equal(template({hello: {}}), '');
});
it('should error on missing object', function() {
shouldThrow(function() {
var template = CompilerContext.compile('{{hello.bar}}', {assumeObjects: true});
template({});
}, Error);
});
it('should error on missing context', function() {
shouldThrow(function() {
var template = CompilerContext.compile('{{hello}}', {assumeObjects: true});
template();
}, Error);
});
it('should error on missing data lookup', function() {
shouldThrow(function() {
var template = CompilerContext.compile('{{@hello.bar}}', {assumeObjects: true});
template();
}, Error);
});
it('should execute blockHelperMissing', function() {
var template = CompilerContext.compile('{{^hello}}foo{{/hello}}', {assumeObjects: true});
equals(template({}), 'foo');
});
});
});
+45 -13
View File
@@ -1,3 +1,4 @@
/*global CompilerContext */
describe('string params mode', function() {
it("arguments to helpers can be retrieved from options hash in string form", function() {
var template = CompilerContext.compile('{{wycats is.a slave.driver}}', {stringParams: true});
@@ -56,9 +57,9 @@ describe('string params mode', function() {
var helpers = {
tomdale: function(desire, noun, trueBool, falseBool, options) {
equal(options.types[0], 'STRING', "the string type is passed");
equal(options.types[1], 'ID', "the expression type is passed");
equal(options.types[2], 'BOOLEAN', "the expression type is passed");
equal(options.types[0], 'StringLiteral', "the string type is passed");
equal(options.types[1], 'PathExpression', "the expression type is passed");
equal(options.types[2], 'BooleanLiteral', "the expression type is passed");
equal(desire, "need", "the string form is passed for strings");
equal(noun, "dad.joke", "the string form is passed for expressions");
equal(trueBool, true, "raw booleans are passed through");
@@ -76,21 +77,21 @@ describe('string params mode', function() {
var helpers = {
tomdale: function(exclamation, options) {
equal(exclamation, "he.says");
equal(options.types[0], "ID");
equal(exclamation, 'he.says');
equal(options.types[0], 'PathExpression');
equal(options.hashTypes.desire, "STRING");
equal(options.hashTypes.noun, "ID");
equal(options.hashTypes.bool, "BOOLEAN");
equal(options.hash.desire, "need");
equal(options.hash.noun, "dad.joke");
equal(options.hashTypes.desire, 'StringLiteral');
equal(options.hashTypes.noun, 'PathExpression');
equal(options.hashTypes.bool, 'BooleanLiteral');
equal(options.hash.desire, 'need');
equal(options.hash.noun, 'dad.joke');
equal(options.hash.bool, true);
return "Helper called";
return 'Helper called';
}
};
var result = template({}, { helpers: helpers });
equal(result, "Helper called");
equal(result, 'Helper called');
});
it("hash parameters get context information", function() {
@@ -101,7 +102,7 @@ describe('string params mode', function() {
var helpers = {
tomdale: function(exclamation, options) {
equal(exclamation, "he.says");
equal(options.types[0], "ID");
equal(options.types[0], 'PathExpression');
equal(options.contexts.length, 1);
equal(options.hashContexts.noun, context);
@@ -142,4 +143,35 @@ describe('string params mode', function() {
equals(result, "STOP ME FROM READING HACKER NEWS I need-a dad.joke wot", "Proper context variable output");
});
it("with nested block ambiguous", function() {
var template = CompilerContext.compile('{{#with content}}{{#view}}{{firstName}} {{lastName}}{{/view}}{{/with}}', {stringParams: true});
var helpers = {
'with': function(options) {
return "WITH";
},
view: function() {
return "VIEW";
}
};
var result = template({}, {helpers: helpers});
equals(result, "WITH");
});
it('should handle DATA', function() {
var template = CompilerContext.compile('{{foo @bar}}', { stringParams: true });
var helpers = {
foo: function(bar, options) {
equal(bar, '@bar');
equal(options.types[0], 'PathExpression');
return 'Foo!';
}
};
var result = template({}, { helpers: helpers });
equal(result, 'Foo!');
});
});
+240
View File
@@ -0,0 +1,240 @@
/*global CompilerContext, Handlebars, shouldCompileTo, shouldThrow */
describe('subexpressions', function() {
it("arg-less helper", function() {
var string = "{{foo (bar)}}!";
var context = {};
var helpers = {
foo: function(val) {
return val+val;
},
bar: function() {
return "LOL";
}
};
shouldCompileTo(string, [context, helpers], "LOLLOL!");
});
it("helper w args", function() {
var string = '{{blog (equal a b)}}';
var context = { bar: "LOL" };
var helpers = {
blog: function(val) {
return "val is " + val;
},
equal: function(x, y) {
return x === y;
}
};
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)}}';
var context = { bar: "LOL" };
var helpers = {
blog: function(val) {
return "val is " + val;
},
equal: function(x, y) {
return x === y;
}
};
shouldCompileTo(string, [context, helpers], "val is true");
});
it('GH-800 : Complex subexpressions', function() {
var context = {a: 'a', b:'b', c:{c:'c'}, d:'d', e: {e: 'e'}};
var helpers = {
dash: function(a, b) {
return a + "-" + b;
},
concat: function(a, b) {
return a + b;
}
};
shouldCompileTo('{{dash "abc" (concat a b)}}', [context, helpers], 'abc-ab');
shouldCompileTo('{{dash d (concat a b)}}', [context, helpers], 'd-ab');
shouldCompileTo('{{dash c.c (concat a b)}}', [context, helpers], 'c-ab');
shouldCompileTo('{{dash (concat a b) c.c}}', [context, helpers], 'ab-c');
shouldCompileTo('{{dash (concat a e.e) c.c}}', [context, helpers], 'ae-c');
});
it("provides each nested helper invocation its own options hash", function() {
var string = '{{equal (equal true true) true}}';
var lastOptions = null;
var helpers = {
equal: function(x, y, options) {
if (!options || options === lastOptions) {
throw new Error("options hash was reused");
}
lastOptions = options;
return x === y;
}
};
shouldCompileTo(string, [{}, helpers], "true");
});
it("with hashes", function() {
var string = '{{blog (equal (equal true true) true fun="yes")}}';
var context = { bar: "LOL" };
var helpers = {
blog: function(val) {
return "val is " + val;
},
equal: function(x, y) {
return x === y;
}
};
shouldCompileTo(string, [context, helpers], "val is true");
});
it("as hashes", function() {
var string = '{{blog fun=(equal (blog fun=1) "val is 1")}}';
var helpers = {
blog: function(options) {
return "val is " + options.hash.fun;
},
equal: function(x, y) {
return x === y;
}
};
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("multiple subexpressions in a hash with context", function() {
var string = '{{input aria-label=(t item.field) placeholder=(t item.placeholder)}}';
var context = {
item: {
field: "Name",
placeholder: "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, [context, 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});
var helpers = {
snog: function(a, b, options) {
equals(a, 'foo');
equals(options.types.length, 2, "string params for outer helper processed correctly");
equals(options.types[0], 'SubExpression', "string params for outer helper processed correctly");
equals(options.types[1], 'PathExpression', "string params for outer helper processed correctly");
return a + b;
},
blorg: function(a, options) {
equals(options.types.length, 1, "string params for inner helper processed correctly");
equals(options.types[0], 'PathExpression', "string params for inner helper processed correctly");
return a;
}
};
var result = template({
foo: {},
yeah: {}
}, {helpers: helpers});
equals(result, "fooyeah");
});
it("as hashes in string params mode", function() {
var template = CompilerContext.compile('{{blog fun=(bork)}}', {stringParams: true});
var helpers = {
blog: function(options) {
equals(options.hashTypes.fun, 'SubExpression');
return "val is " + options.hash.fun;
},
bork: function() {
return "BORK";
}
};
var result = template({}, {helpers: helpers});
equals(result, "val is BORK");
});
it("subexpression functions on the context", function() {
var string = "{{foo (bar)}}!";
var context = {
bar: function() {
return "LOL";
}
};
var helpers = {
foo: function(val) {
return val+val;
}
};
shouldCompileTo(string, [context, helpers], "LOLLOL!");
});
it("subexpressions can't just be property lookups", function() {
var string = "{{foo (bar)}}!";
var context = {
bar: "LOL"
};
var helpers = {
foo: function(val) {
return val+val;
}
};
shouldThrow(function() {
shouldCompileTo(string, [context, helpers], "LOLLOL!");
});
});
});
+186 -124
View File
@@ -1,13 +1,13 @@
var should = require('should');
should.Assertion.prototype.match_tokens = function(tokens) {
this.obj.forEach(function(value, index) {
value.name.should.equal(tokens[index]);
});
};
should.Assertion.prototype.be_token = function(name, text) {
this.obj.should.eql({name: name, text: text});
};
/*global Handlebars */
function shouldMatchTokens(result, tokens) {
for (var index = 0; index < result.length; index++) {
equals(result[index].name, tokens[index]);
}
}
function shouldBeToken(result, name, text) {
equals(result.name, name);
equals(result.text, text);
}
describe('Tokenizer', function() {
if (!Handlebars.Parser) {
@@ -35,324 +35,386 @@ describe('Tokenizer', function() {
it('tokenizes a simple mustache as "OPEN ID CLOSE"', function() {
var result = tokenize("{{foo}}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE']);
result[1].should.be_token("ID", "foo");
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[1], "ID", "foo");
});
it('supports unescaping with &', function() {
var result = tokenize("{{&bar}}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE']);
result[0].should.be_token("OPEN", "{{&");
result[1].should.be_token("ID", "bar");
shouldBeToken(result[0], "OPEN", "{{&");
shouldBeToken(result[1], "ID", "bar");
});
it('supports unescaping with {{{', function() {
var result = tokenize("{{{bar}}}");
result.should.match_tokens(['OPEN_UNESCAPED', 'ID', 'CLOSE_UNESCAPED']);
shouldMatchTokens(result, ['OPEN_UNESCAPED', 'ID', 'CLOSE_UNESCAPED']);
result[1].should.be_token("ID", "bar");
shouldBeToken(result[1], "ID", "bar");
});
it('supports escaping delimiters', function() {
var result = tokenize("{{foo}} \\{{bar}} {{baz}}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
result[3].should.be_token("CONTENT", " ");
result[4].should.be_token("CONTENT", "{{bar}} ");
shouldBeToken(result[3], "CONTENT", " ");
shouldBeToken(result[4], "CONTENT", "{{bar}} ");
});
it('supports escaping multiple delimiters', function() {
var result = tokenize("{{foo}} \\{{bar}} \\{{baz}}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'CONTENT']);
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'CONTENT']);
result[3].should.be_token("CONTENT", " ");
result[4].should.be_token("CONTENT", "{{bar}} ");
result[5].should.be_token("CONTENT", "{{baz}}");
shouldBeToken(result[3], "CONTENT", " ");
shouldBeToken(result[4], "CONTENT", "{{bar}} ");
shouldBeToken(result[5], "CONTENT", "{{baz}}");
});
it('supports escaping a triple stash', function() {
var result = tokenize("{{foo}} \\{{{bar}}} {{baz}}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
result[4].should.be_token("CONTENT", "{{{bar}}} ");
shouldBeToken(result[4], "CONTENT", "{{{bar}}} ");
});
it('supports escaping escape character', function() {
var result = tokenize("{{foo}} \\\\{{bar}} {{baz}}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
result[3].should.be_token("CONTENT", " \\");
result[5].should.be_token("ID", "bar");
shouldBeToken(result[3], "CONTENT", " \\");
shouldBeToken(result[5], "ID", "bar");
});
it('supports escaping multiple escape characters', function() {
var result = tokenize("{{foo}} \\\\{{bar}} \\\\{{baz}}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
result[3].should.be_token("CONTENT", " \\");
result[5].should.be_token("ID", "bar");
result[7].should.be_token("CONTENT", " \\");
result[9].should.be_token("ID", "baz");
shouldBeToken(result[3], "CONTENT", " \\");
shouldBeToken(result[5], "ID", "bar");
shouldBeToken(result[7], "CONTENT", " \\");
shouldBeToken(result[9], "ID", "baz");
});
it('supports mixed escaped delimiters and escaped escape characters', function() {
it('supports escaped mustaches after escaped escape characters', function() {
var result = tokenize("{{foo}} \\\\{{bar}} \\{{baz}}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'CONTENT']);
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'CONTENT']);
result[3].should.be_token("CONTENT", " \\");
result[4].should.be_token("OPEN", "{{");
result[5].should.be_token("ID", "bar");
result[7].should.be_token("CONTENT", " ");
result[8].should.be_token("CONTENT", "{{baz}}");
shouldBeToken(result[3], "CONTENT", " \\");
shouldBeToken(result[4], "OPEN", "{{");
shouldBeToken(result[5], "ID", "bar");
shouldBeToken(result[7], "CONTENT", " ");
shouldBeToken(result[8], "CONTENT", "{{baz}}");
});
it('supports escaped escape characters after escaped mustaches', function() {
var result = tokenize("{{foo}} \\{{bar}} \\\\{{baz}}");
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'CONTENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[4], "CONTENT", "{{bar}} ");
shouldBeToken(result[5], "CONTENT", "\\");
shouldBeToken(result[6], "OPEN", "{{");
shouldBeToken(result[7], "ID", "baz");
});
it('supports escaped escape character on a triple stash', function() {
var result = tokenize("{{foo}} \\\\{{{bar}}} {{baz}}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN_UNESCAPED', 'ID', 'CLOSE_UNESCAPED', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE', 'CONTENT', 'OPEN_UNESCAPED', 'ID', 'CLOSE_UNESCAPED', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
result[3].should.be_token("CONTENT", " \\");
result[5].should.be_token("ID", "bar");
shouldBeToken(result[3], "CONTENT", " \\");
shouldBeToken(result[5], "ID", "bar");
});
it('tokenizes a simple path', function() {
var result = tokenize("{{foo/bar}}");
result.should.match_tokens(['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('allows dot notation', function() {
var result = tokenize("{{foo.bar}}");
result.should.match_tokens(['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
tokenize("{{foo.bar.baz}}").should.match_tokens(['OPEN', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldMatchTokens(tokenize("{{foo.bar.baz}}"), ['OPEN', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('allows path literals with []', function() {
var result = tokenize("{{foo.[bar]}}");
result.should.match_tokens(['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('allows multiple path literals on a line with []', function() {
var result = tokenize("{{foo.[bar]}}{{foo.[baz]}}");
result.should.match_tokens(['OPEN', 'ID', 'SEP', 'ID', 'CLOSE', 'OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE', 'OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('tokenizes {{.}} as OPEN ID CLOSE', function() {
var result = tokenize("{{.}}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE']);
});
it('tokenizes a path as "OPEN (ID SEP)* ID CLOSE"', function() {
var result = tokenize("{{../foo/bar}}");
result.should.match_tokens(['OPEN', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
result[1].should.be_token("ID", "..");
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldBeToken(result[1], "ID", "..");
});
it('tokenizes a path with .. as a parent path', function() {
var result = tokenize("{{../foo.bar}}");
result.should.match_tokens(['OPEN', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
result[1].should.be_token("ID", "..");
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldBeToken(result[1], "ID", "..");
});
it('tokenizes a path with this/foo as OPEN ID SEP ID CLOSE', function() {
var result = tokenize("{{this/foo}}");
result.should.match_tokens(['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
result[1].should.be_token("ID", "this");
result[3].should.be_token("ID", "foo");
shouldMatchTokens(result, ['OPEN', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldBeToken(result[1], "ID", "this");
shouldBeToken(result[3], "ID", "foo");
});
it('tokenizes a simple mustache with spaces as "OPEN ID CLOSE"', function() {
var result = tokenize("{{ foo }}");
result.should.match_tokens(['OPEN', 'ID', 'CLOSE']);
result[1].should.be_token("ID", "foo");
shouldMatchTokens(result, ['OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[1], "ID", "foo");
});
it('tokenizes a simple mustache with line breaks as "OPEN ID ID CLOSE"', function() {
var result = tokenize("{{ foo \n bar }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'CLOSE']);
result[1].should.be_token("ID", "foo");
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'CLOSE']);
shouldBeToken(result[1], "ID", "foo");
});
it('tokenizes raw content as "CONTENT"', function() {
var result = tokenize("foo {{ bar }} baz");
result.should.match_tokens(['CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT']);
result[0].should.be_token("CONTENT", "foo ");
result[4].should.be_token("CONTENT", " baz");
shouldMatchTokens(result, ['CONTENT', 'OPEN', 'ID', 'CLOSE', 'CONTENT']);
shouldBeToken(result[0], "CONTENT", "foo ");
shouldBeToken(result[4], "CONTENT", " baz");
});
it('tokenizes a partial as "OPEN_PARTIAL ID CLOSE"', function() {
var result = tokenize("{{> foo}}");
result.should.match_tokens(['OPEN_PARTIAL', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN_PARTIAL', 'ID', 'CLOSE']);
});
it('tokenizes a partial with context as "OPEN_PARTIAL ID ID CLOSE"', function() {
var result = tokenize("{{> foo bar }}");
result.should.match_tokens(['OPEN_PARTIAL', 'ID', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN_PARTIAL', 'ID', 'ID', 'CLOSE']);
});
it('tokenizes a partial without spaces as "OPEN_PARTIAL ID CLOSE"', function() {
var result = tokenize("{{>foo}}");
result.should.match_tokens(['OPEN_PARTIAL', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN_PARTIAL', 'ID', 'CLOSE']);
});
it('tokenizes a partial space at the }); as "OPEN_PARTIAL ID CLOSE"', function() {
var result = tokenize("{{>foo }}");
result.should.match_tokens(['OPEN_PARTIAL', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN_PARTIAL', 'ID', 'CLOSE']);
});
it('tokenizes a partial space at the }); as "OPEN_PARTIAL ID CLOSE"', function() {
var result = tokenize("{{>foo/bar.baz }}");
result.should.match_tokens(['OPEN_PARTIAL', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN_PARTIAL', 'ID', 'SEP', 'ID', 'SEP', 'ID', 'CLOSE']);
});
it('tokenizes a comment as "COMMENT"', function() {
var result = tokenize("foo {{! this is a comment }} bar {{ baz }}");
result.should.match_tokens(['CONTENT', 'COMMENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
result[1].should.be_token("COMMENT", " this is a comment ");
shouldMatchTokens(result, ['CONTENT', 'COMMENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[1], "COMMENT", "{{! this is a comment }}");
});
it('tokenizes a block comment as "COMMENT"', function() {
var result = tokenize("foo {{!-- this is a {{comment}} --}} bar {{ baz }}");
result.should.match_tokens(['CONTENT', 'COMMENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
result[1].should.be_token("COMMENT", " this is a {{comment}} ");
shouldMatchTokens(result, ['CONTENT', 'COMMENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[1], "COMMENT", "{{!-- this is a {{comment}} --}}");
});
it('tokenizes a block comment with whitespace as "COMMENT"', function() {
var result = tokenize("foo {{!-- this is a\n{{comment}}\n--}} bar {{ baz }}");
result.should.match_tokens(['CONTENT', 'COMMENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
result[1].should.be_token("COMMENT", " this is a\n{{comment}}\n");
shouldMatchTokens(result, ['CONTENT', 'COMMENT', 'CONTENT', 'OPEN', 'ID', 'CLOSE']);
shouldBeToken(result[1], "COMMENT", "{{!-- this is a\n{{comment}}\n--}}");
});
it('tokenizes open and closing blocks as OPEN_BLOCK, ID, CLOSE ..., OPEN_ENDBLOCK ID CLOSE', function() {
var result = tokenize("{{#foo}}content{{/foo}}");
result.should.match_tokens(['OPEN_BLOCK', 'ID', 'CLOSE', 'CONTENT', 'OPEN_ENDBLOCK', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN_BLOCK', 'ID', 'CLOSE', 'CONTENT', 'OPEN_ENDBLOCK', 'ID', 'CLOSE']);
});
it('tokenizes inverse sections as "OPEN_INVERSE CLOSE"', function() {
tokenize("{{^}}").should.match_tokens(['OPEN_INVERSE', 'CLOSE']);
tokenize("{{else}}").should.match_tokens(['OPEN_INVERSE', 'CLOSE']);
tokenize("{{ else }}").should.match_tokens(['OPEN_INVERSE', 'CLOSE']);
it('tokenizes inverse sections as "INVERSE"', function() {
shouldMatchTokens(tokenize("{{^}}"), ['INVERSE']);
shouldMatchTokens(tokenize("{{else}}"), ['INVERSE']);
shouldMatchTokens(tokenize("{{ else }}"), ['INVERSE']);
});
it('tokenizes inverse sections with ID as "OPEN_INVERSE ID CLOSE"', function() {
var result = tokenize("{{^foo}}");
result.should.match_tokens(['OPEN_INVERSE', 'ID', 'CLOSE']);
result[1].should.be_token("ID", "foo");
shouldMatchTokens(result, ['OPEN_INVERSE', 'ID', 'CLOSE']);
shouldBeToken(result[1], "ID", "foo");
});
it('tokenizes inverse sections with ID and spaces as "OPEN_INVERSE ID CLOSE"', function() {
var result = tokenize("{{^ foo }}");
result.should.match_tokens(['OPEN_INVERSE', 'ID', 'CLOSE']);
result[1].should.be_token("ID", "foo");
shouldMatchTokens(result, ['OPEN_INVERSE', 'ID', 'CLOSE']);
shouldBeToken(result[1], "ID", "foo");
});
it('tokenizes mustaches with params as "OPEN ID ID ID CLOSE"', function() {
var result = tokenize("{{ foo bar baz }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'ID', 'CLOSE']);
result[1].should.be_token("ID", "foo");
result[2].should.be_token("ID", "bar");
result[3].should.be_token("ID", "baz");
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'CLOSE']);
shouldBeToken(result[1], "ID", "foo");
shouldBeToken(result[2], "ID", "bar");
shouldBeToken(result[3], "ID", "baz");
});
it('tokenizes mustaches with String params as "OPEN ID ID STRING CLOSE"', function() {
var result = tokenize("{{ foo bar \"baz\" }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'STRING', 'CLOSE']);
result[3].should.be_token("STRING", "baz");
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'STRING', 'CLOSE']);
shouldBeToken(result[3], "STRING", "baz");
});
it('tokenizes mustaches with String params using single quotes as "OPEN ID ID STRING CLOSE"', function() {
var result = tokenize("{{ foo bar \'baz\' }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'STRING', 'CLOSE']);
result[3].should.be_token("STRING", "baz");
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'STRING', 'CLOSE']);
shouldBeToken(result[3], "STRING", "baz");
});
it('tokenizes String params with spaces inside as "STRING"', function() {
var result = tokenize("{{ foo bar \"baz bat\" }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'STRING', 'CLOSE']);
result[3].should.be_token("STRING", "baz bat");
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'STRING', 'CLOSE']);
shouldBeToken(result[3], "STRING", "baz bat");
});
it('tokenizes String params with escapes quotes as STRING', function() {
var result = tokenize('{{ foo "bar\\"baz" }}');
result.should.match_tokens(['OPEN', 'ID', 'STRING', 'CLOSE']);
result[2].should.be_token("STRING", 'bar"baz');
shouldMatchTokens(result, ['OPEN', 'ID', 'STRING', 'CLOSE']);
shouldBeToken(result[2], "STRING", 'bar"baz');
});
it('tokenizes String params using single quotes with escapes quotes as STRING', function() {
var result = tokenize("{{ foo 'bar\\'baz' }}");
result.should.match_tokens(['OPEN', 'ID', 'STRING', 'CLOSE']);
result[2].should.be_token("STRING", "bar'baz");
shouldMatchTokens(result, ['OPEN', 'ID', 'STRING', 'CLOSE']);
shouldBeToken(result[2], "STRING", "bar'baz");
});
it('tokenizes numbers', function() {
var result = tokenize('{{ foo 1 }}');
result.should.match_tokens(['OPEN', 'ID', 'INTEGER', 'CLOSE']);
result[2].should.be_token("INTEGER", "1");
shouldMatchTokens(result, ['OPEN', 'ID', 'NUMBER', 'CLOSE']);
shouldBeToken(result[2], "NUMBER", "1");
result = tokenize('{{ foo 1.1 }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'NUMBER', 'CLOSE']);
shouldBeToken(result[2], "NUMBER", "1.1");
result = tokenize('{{ foo -1 }}');
result.should.match_tokens(['OPEN', 'ID', 'INTEGER', 'CLOSE']);
result[2].should.be_token("INTEGER", "-1");
shouldMatchTokens(result, ['OPEN', 'ID', 'NUMBER', 'CLOSE']);
shouldBeToken(result[2], "NUMBER", "-1");
result = tokenize('{{ foo -1.1 }}');
shouldMatchTokens(result, ['OPEN', 'ID', 'NUMBER', 'CLOSE']);
shouldBeToken(result[2], "NUMBER", "-1.1");
});
it('tokenizes booleans', function() {
var result = tokenize('{{ foo true }}');
result.should.match_tokens(['OPEN', 'ID', 'BOOLEAN', 'CLOSE']);
result[2].should.be_token("BOOLEAN", "true");
shouldMatchTokens(result, ['OPEN', 'ID', 'BOOLEAN', 'CLOSE']);
shouldBeToken(result[2], "BOOLEAN", "true");
result = tokenize('{{ foo false }}');
result.should.match_tokens(['OPEN', 'ID', 'BOOLEAN', 'CLOSE']);
result[2].should.be_token("BOOLEAN", "false");
shouldMatchTokens(result, ['OPEN', 'ID', 'BOOLEAN', 'CLOSE']);
shouldBeToken(result[2], "BOOLEAN", "false");
});
it('tokenizes hash arguments', function() {
var result = tokenize("{{ foo bar=baz }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'EQUALS', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'EQUALS', 'ID', 'CLOSE']);
result = tokenize("{{ foo bar baz=bat }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'ID', 'CLOSE']);
result = tokenize("{{ foo bar baz=1 }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'INTEGER', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'NUMBER', 'CLOSE']);
result = tokenize("{{ foo bar baz=true }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'BOOLEAN', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'BOOLEAN', 'CLOSE']);
result = tokenize("{{ foo bar baz=false }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'BOOLEAN', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'BOOLEAN', 'CLOSE']);
result = tokenize("{{ foo bar\n baz=bat }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'ID', 'CLOSE']);
result = tokenize("{{ foo bar baz=\"bat\" }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'STRING', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'STRING', 'CLOSE']);
result = tokenize("{{ foo bar baz=\"bat\" bam=wot }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'STRING', 'ID', 'EQUALS', 'ID', 'CLOSE']);
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'STRING', 'ID', 'EQUALS', 'ID', 'CLOSE']);
result = tokenize("{{foo omg bar=baz bat=\"bam\"}}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'ID', 'ID', 'EQUALS', 'STRING', 'CLOSE']);
result[2].should.be_token("ID", "omg");
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'ID', 'EQUALS', 'ID', 'ID', 'EQUALS', 'STRING', 'CLOSE']);
shouldBeToken(result[2], "ID", "omg");
});
it('tokenizes special @ identifiers', function() {
var result = tokenize("{{ @foo }}");
result.should.match_tokens(['OPEN', 'DATA', 'ID', 'CLOSE']);
result[2].should.be_token("ID", "foo");
shouldMatchTokens(result, ['OPEN', 'DATA', 'ID', 'CLOSE']);
shouldBeToken(result[2], "ID", "foo");
result = tokenize("{{ foo @bar }}");
result.should.match_tokens(['OPEN', 'ID', 'DATA', 'ID', 'CLOSE']);
result[3].should.be_token("ID", "bar");
shouldMatchTokens(result, ['OPEN', 'ID', 'DATA', 'ID', 'CLOSE']);
shouldBeToken(result[3], "ID", "bar");
result = tokenize("{{ foo bar=@baz }}");
result.should.match_tokens(['OPEN', 'ID', 'ID', 'EQUALS', 'DATA', 'ID', 'CLOSE']);
result[5].should.be_token("ID", "baz");
shouldMatchTokens(result, ['OPEN', 'ID', 'ID', 'EQUALS', 'DATA', 'ID', 'CLOSE']);
shouldBeToken(result[5], "ID", "baz");
});
it('does not time out in a mustache with a single } followed by EOF', function() {
tokenize("{{foo}").should.match_tokens(['OPEN', 'ID']);
shouldMatchTokens(tokenize("{{foo}"), ['OPEN', 'ID']);
});
it('does not time out in a mustache when invalid ID characters are used', function() {
tokenize("{{foo & }}").should.match_tokens(['OPEN', 'ID']);
shouldMatchTokens(tokenize("{{foo & }}"), ['OPEN', 'ID']);
});
it('tokenizes subexpressions', function() {
var result = tokenize("{{foo (bar)}}");
shouldMatchTokens(result, ['OPEN', 'ID', 'OPEN_SEXPR', 'ID', 'CLOSE_SEXPR', 'CLOSE']);
shouldBeToken(result[1], "ID", "foo");
shouldBeToken(result[3], "ID", "bar");
result = tokenize("{{foo (a-x b-y)}}");
shouldMatchTokens(result, ['OPEN', 'ID', 'OPEN_SEXPR', 'ID', 'ID', 'CLOSE_SEXPR', 'CLOSE']);
shouldBeToken(result[1], "ID", "foo");
shouldBeToken(result[3], "ID", "a-x");
shouldBeToken(result[4], "ID", "b-y");
});
it('tokenizes nested subexpressions', function() {
var result = tokenize("{{foo (bar (lol rofl)) (baz)}}");
shouldMatchTokens(result, ['OPEN', 'ID', 'OPEN_SEXPR', 'ID', 'OPEN_SEXPR', 'ID', 'ID', 'CLOSE_SEXPR', 'CLOSE_SEXPR', 'OPEN_SEXPR', 'ID', 'CLOSE_SEXPR', 'CLOSE']);
shouldBeToken(result[3], "ID", "bar");
shouldBeToken(result[5], "ID", "lol");
shouldBeToken(result[6], "ID", "rofl");
shouldBeToken(result[10], "ID", "baz");
});
it('tokenizes nested subexpressions: literals', function() {
var result = tokenize("{{foo (bar (lol true) false) (baz 1) (blah 'b') (blorg \"c\")}}");
shouldMatchTokens(result, ['OPEN', 'ID', 'OPEN_SEXPR', 'ID', 'OPEN_SEXPR', 'ID', 'BOOLEAN', 'CLOSE_SEXPR', 'BOOLEAN', 'CLOSE_SEXPR', 'OPEN_SEXPR', 'ID', 'NUMBER', 'CLOSE_SEXPR', 'OPEN_SEXPR', 'ID', 'STRING', 'CLOSE_SEXPR', 'OPEN_SEXPR', 'ID', 'STRING', 'CLOSE_SEXPR', 'CLOSE']);
});
it('tokenizes block params', function() {
var result = tokenize("{{#foo as |bar|}}");
shouldMatchTokens(result, ['OPEN_BLOCK', 'ID', 'OPEN_BLOCK_PARAMS', 'ID', 'CLOSE_BLOCK_PARAMS', 'CLOSE']);
result = tokenize("{{#foo as |bar baz|}}");
shouldMatchTokens(result, ['OPEN_BLOCK', 'ID', 'OPEN_BLOCK_PARAMS', 'ID', 'ID', 'CLOSE_BLOCK_PARAMS', 'CLOSE']);
result = tokenize("{{#foo as | bar baz |}}");
shouldMatchTokens(result, ['OPEN_BLOCK', 'ID', 'OPEN_BLOCK_PARAMS', 'ID', 'ID', 'CLOSE_BLOCK_PARAMS', 'CLOSE']);
result = tokenize("{{#foo as as | bar baz |}}");
shouldMatchTokens(result, ['OPEN_BLOCK', 'ID', 'ID', 'OPEN_BLOCK_PARAMS', 'ID', 'ID', 'CLOSE_BLOCK_PARAMS', 'CLOSE']);
result = tokenize("{{else foo as |bar baz|}}");
shouldMatchTokens(result, ['OPEN_INVERSE_CHAIN', 'ID', 'OPEN_BLOCK_PARAMS', 'ID', 'ID', 'CLOSE_BLOCK_PARAMS', 'CLOSE']);
});
});
+195
View File
@@ -0,0 +1,195 @@
/*global CompilerContext */
describe('track ids', function() {
var context;
beforeEach(function() {
context = {is: {a: 'foo'}, slave: {driver: 'bar'}};
});
it('should not include anything without the flag', function() {
var template = CompilerContext.compile('{{wycats is.a slave.driver}}');
var helpers = {
wycats: function(passiveVoice, noun, options) {
equal(options.ids, undefined);
equal(options.hashIds, undefined);
return 'success';
}
};
equals(template({}, {helpers: helpers}), 'success');
});
it('should include argument ids', function() {
var template = CompilerContext.compile('{{wycats is.a slave.driver}}', {trackIds: true});
var helpers = {
wycats: function(passiveVoice, noun, options) {
equal(options.ids[0], 'is.a');
equal(options.ids[1], 'slave.driver');
return "HELP ME MY BOSS " + options.ids[0] + ':' + passiveVoice + ' ' + options.ids[1] + ':' + noun;
}
};
equals(template(context, {helpers: helpers}), 'HELP ME MY BOSS is.a:foo slave.driver:bar');
});
it('should include hash ids', function() {
var template = CompilerContext.compile('{{wycats bat=is.a baz=slave.driver}}', {trackIds: true});
var helpers = {
wycats: function(options) {
equal(options.hashIds.bat, 'is.a');
equal(options.hashIds.baz, 'slave.driver');
return "HELP ME MY BOSS " + options.hashIds.bat + ':' + options.hash.bat + ' ' + options.hashIds.baz + ':' + options.hash.baz;
}
};
equals(template(context, {helpers: helpers}), 'HELP ME MY BOSS is.a:foo slave.driver:bar');
});
it('should note ../ and ./ references', function() {
var template = CompilerContext.compile('{{wycats ./is.a ../slave.driver}}', {trackIds: true});
var helpers = {
wycats: function(passiveVoice, noun, options) {
equal(options.ids[0], 'is.a');
equal(options.ids[1], '../slave.driver');
return "HELP ME MY BOSS " + options.ids[0] + ':' + passiveVoice + ' ' + options.ids[1] + ':' + noun;
}
};
equals(template(context, {helpers: helpers}), 'HELP ME MY BOSS is.a:foo ../slave.driver:undefined');
});
it('should note @data references', function() {
var template = CompilerContext.compile('{{wycats @is.a @slave.driver}}', {trackIds: true});
var helpers = {
wycats: function(passiveVoice, noun, options) {
equal(options.ids[0], '@is.a');
equal(options.ids[1], '@slave.driver');
return "HELP ME MY BOSS " + options.ids[0] + ':' + passiveVoice + ' ' + options.ids[1] + ':' + noun;
}
};
equals(template({}, {helpers: helpers, data:context}), 'HELP ME MY BOSS @is.a:foo @slave.driver:bar');
});
it('should return null for constants', function() {
var template = CompilerContext.compile('{{wycats 1 "foo" key=false}}', {trackIds: true});
var helpers = {
wycats: function(passiveVoice, noun, options) {
equal(options.ids[0], null);
equal(options.ids[1], null);
equal(options.hashIds.key, null);
return "HELP ME MY BOSS " + passiveVoice + ' ' + noun + ' ' + options.hash.key;
}
};
equals(template(context, {helpers: helpers}), 'HELP ME MY BOSS 1 foo false');
});
it('should return true for subexpressions', function() {
var template = CompilerContext.compile('{{wycats (sub)}}', {trackIds: true});
var helpers = {
sub: function() { return 1; },
wycats: function(passiveVoice, options) {
equal(options.ids[0], true);
return "HELP ME MY BOSS " + passiveVoice;
}
};
equals(template(context, {helpers: helpers}), 'HELP ME MY BOSS 1');
});
it('should use block param paths', function() {
var template = CompilerContext.compile('{{#doIt as |is|}}{{wycats is.a slave.driver is}}{{/doIt}}', {trackIds: true});
var helpers = {
doIt: function(options) {
var blockParams = [this.is];
blockParams.path = ['zomg'];
return options.fn(this, {blockParams: blockParams});
},
wycats: function(passiveVoice, noun, blah, options) {
equal(options.ids[0], 'zomg.a');
equal(options.ids[1], 'slave.driver');
equal(options.ids[2], 'zomg');
return "HELP ME MY BOSS " + options.ids[0] + ':' + passiveVoice + ' ' + options.ids[1] + ':' + noun;
}
};
equals(template(context, {helpers: helpers}), 'HELP ME MY BOSS zomg.a:foo slave.driver:bar');
});
describe('builtin helpers', function() {
var helpers = {
wycats: function(name, options) {
return name + ':' + options.data.contextPath + '\n';
}
};
describe('#each', function() {
it('should track contextPath for arrays', function() {
var template = CompilerContext.compile('{{#each array}}{{wycats name}}{{/each}}', {trackIds: true});
equals(template({array: [{name: 'foo'}, {name: 'bar'}]}, {helpers: helpers}), 'foo:array.0\nbar:array.1\n');
});
it('should track contextPath for keys', function() {
var template = CompilerContext.compile('{{#each object}}{{wycats name}}{{/each}}', {trackIds: true});
equals(template({object: {foo: {name: 'foo'}, bar: {name: 'bar'}}}, {helpers: helpers}), 'foo:object.foo\nbar:object.bar\n');
});
it('should handle nesting', function() {
var template = CompilerContext.compile('{{#each .}}{{#each .}}{{wycats name}}{{/each}}{{/each}}', {trackIds: true});
equals(template({array: [{name: 'foo'}, {name: 'bar'}]}, {helpers: helpers}), 'foo:.array..0\nbar:.array..1\n');
});
it('should handle block params', function() {
var helpers = {
wycats: function(name, options) {
return name + ':' + options.ids[0] + '\n';
}
};
var template = CompilerContext.compile('{{#each array as |value|}}{{wycats value.name}}{{/each}}', {trackIds: true});
equals(template({array: [{name: 'foo'}, {name: 'bar'}]}, {helpers: helpers}), 'foo:array.0.name\nbar:array.1.name\n');
});
});
describe('#with', function() {
it('should track contextPath', function() {
var template = CompilerContext.compile('{{#with field}}{{wycats name}}{{/with}}', {trackIds: true});
equals(template({field: {name: 'foo'}}, {helpers: helpers}), 'foo:field\n');
});
it('should handle nesting', function() {
var template = CompilerContext.compile('{{#with bat}}{{#with field}}{{wycats name}}{{/with}}{{/with}}', {trackIds: true});
equals(template({bat: {field: {name: 'foo'}}}, {helpers: helpers}), 'foo:bat.field\n');
});
});
describe('#blockHelperMissing', function() {
it('should track contextPath for arrays', function() {
var template = CompilerContext.compile('{{#field}}{{wycats name}}{{/field}}', {trackIds: true});
equals(template({field: [{name: 'foo'}]}, {helpers: helpers}), 'foo:field.0\n');
});
it('should track contextPath for keys', function() {
var template = CompilerContext.compile('{{#field}}{{wycats name}}{{/field}}', {trackIds: true});
equals(template({field: {name: 'foo'}}, {helpers: helpers}), 'foo:field\n');
});
it('should handle nesting', function() {
var template = CompilerContext.compile('{{#bat}}{{#field}}{{wycats name}}{{/field}}{{/bat}}', {trackIds: true});
equals(template({bat: {field: {name: 'foo'}}}, {helpers: helpers}), 'foo:bat.field\n');
});
});
});
});
+89
View File
@@ -0,0 +1,89 @@
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/node_modules/mocha/mocha.css" />
<style>
.headless .suite > h1,
.headless .test.pass {
display: none;
}
</style>
<script>
// Show only errors in "headless", non-interactive mode.
if (/headless=true/.test(location.href)) {
document.documentElement.className = 'headless';
}
</script>
<script src="/node_modules/mocha/mocha.js"></script>
<script>
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>
<script>
requirejs.config({
paths: {
'handlebars.runtime': '/dist/handlebars.runtime'
}
});
</script>
<script>
onload = function(){
require(['handlebars.runtime'], function(Handlebars) {
describe('runtime', function() {
it('should load', function() {
equal(!!Handlebars.template, true);
equal(!!Handlebars.VERSION, true);
});
});
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();
}
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>
<body>
<div id="mocha"></div>
</body>
</html>
+109
View File
@@ -0,0 +1,109 @@
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/node_modules/mocha/mocha.css" />
<style>
.headless .suite > h1,
.headless .test.pass {
display: none;
}
</style>
<script>
// Show only errors in "headless", non-interactive mode.
if (/headless=true/.test(location.href)) {
document.documentElement.className = 'headless';
}
</script>
<script src="/node_modules/mocha/mocha.js"></script>
<script>
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>
<script>
requirejs.config({
paths: {
handlebars: '/dist/handlebars',
tests: '/tmp/tests'
}
});
var CompilerContext = {
compile: function(template, options) {
var templateSpec = handlebarsEnv.precompile(template, options);
return handlebarsEnv.template(safeEval(templateSpec));
},
compileWithPartial: function(template, options) {
return handlebarsEnv.compile(template, options);
}
};
function safeEval(templateSpec) {
try {
var ret;
eval('ret = ' + templateSpec);
return ret;
} catch (err) {
console.error(templateSpec);
throw err;
}
}
</script>
<script>
onload = function(){
require(['handlebars'], function(Handlebars) {
window.Handlebars = Handlebars;
require(['tests'], 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();
}
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>
<body>
<div id="mocha"></div>
</body>
</html>
+45 -21
View File
@@ -1,11 +1,13 @@
/*global shouldCompileTo */
/*global Handlebars, shouldCompileTo */
describe('utils', function() {
describe('#SafeString', function() {
it("constructing a safestring from a string and checking its type", function() {
var safe = new Handlebars.SafeString("testing 1, 2, 3");
safe.should.be.instanceof(Handlebars.SafeString);
(safe == "testing 1, 2, 3").should.equal(true, "SafeString is equivalent to its underlying string");
if (!(safe instanceof Handlebars.SafeString)) {
throw new Error('Must be instance of SafeString');
}
equals(safe == 'testing 1, 2, 3', true, 'SafeString is equivalent to its underlying string');
});
it("it should not escape SafeString properties", function() {
@@ -17,41 +19,63 @@ describe('utils', function() {
describe('#escapeExpression', function() {
it('shouhld escape html', function() {
Handlebars.Utils.escapeExpression('foo<&"\'>').should.equal('foo&lt;&amp;&quot;&#x27;&gt;');
equals(Handlebars.Utils.escapeExpression('foo<&"\'>'), 'foo&lt;&amp;&quot;&#x27;&gt;');
});
it('should not escape SafeString', function() {
var string = new Handlebars.SafeString('foo<&"\'>');
Handlebars.Utils.escapeExpression(string).should.equal('foo<&"\'>');
equals(Handlebars.Utils.escapeExpression(string), 'foo<&"\'>');
var obj = {
toHTML: function() {
return 'foo<&"\'>';
}
};
equals(Handlebars.Utils.escapeExpression(obj), 'foo<&"\'>');
});
it('should handle falsy', function() {
Handlebars.Utils.escapeExpression('').should.equal('');
Handlebars.Utils.escapeExpression(undefined).should.equal('');
Handlebars.Utils.escapeExpression(null).should.equal('');
Handlebars.Utils.escapeExpression(false).should.equal('');
equals(Handlebars.Utils.escapeExpression(''), '');
equals(Handlebars.Utils.escapeExpression(undefined), '');
equals(Handlebars.Utils.escapeExpression(null), '');
Handlebars.Utils.escapeExpression(0).should.equal('0');
equals(Handlebars.Utils.escapeExpression(false), 'false');
equals(Handlebars.Utils.escapeExpression(0), '0');
});
it('should handle empty objects', function() {
Handlebars.Utils.escapeExpression({}).should.equal({}.toString());
Handlebars.Utils.escapeExpression([]).should.equal([].toString());
equals(Handlebars.Utils.escapeExpression({}), {}.toString());
equals(Handlebars.Utils.escapeExpression([]), [].toString());
});
});
describe('#isEmpty', function() {
it('should not be empty', function() {
Handlebars.Utils.isEmpty(undefined).should.equal(true);
Handlebars.Utils.isEmpty(null).should.equal(true);
Handlebars.Utils.isEmpty(false).should.equal(true);
Handlebars.Utils.isEmpty('').should.equal(true);
Handlebars.Utils.isEmpty([]).should.equal(true);
equals(Handlebars.Utils.isEmpty(undefined), true);
equals(Handlebars.Utils.isEmpty(null), true);
equals(Handlebars.Utils.isEmpty(false), true);
equals(Handlebars.Utils.isEmpty(''), true);
equals(Handlebars.Utils.isEmpty([]), true);
});
it('should be empty', function() {
Handlebars.Utils.isEmpty(0).should.equal(false);
Handlebars.Utils.isEmpty([1]).should.equal(false);
Handlebars.Utils.isEmpty('foo').should.equal(false);
Handlebars.Utils.isEmpty({bar: 1}).should.equal(false);
equals(Handlebars.Utils.isEmpty(0), false);
equals(Handlebars.Utils.isEmpty([1]), false);
equals(Handlebars.Utils.isEmpty('foo'), false);
equals(Handlebars.Utils.isEmpty({bar: 1}), false);
});
});
describe('#extend', function() {
it('should ignore prototype values', function() {
function A() {
this.a = 1;
}
A.prototype.b = 4;
var b = {b: 2};
Handlebars.Utils.extend(b, new A());
equals(b.a, 1);
equals(b.b, 2);
});
});
});
+143
View File
@@ -0,0 +1,143 @@
/*global Handlebars, shouldThrow */
describe('Visitor', function() {
if (!Handlebars.Visitor || !Handlebars.print) {
return;
}
it('should provide coverage', function() {
// Simply run the thing and make sure it does not fail and that all of the
// stub methods are executed
var visitor = new Handlebars.Visitor();
visitor.accept(Handlebars.parse('{{foo}}{{#foo (bar 1 "1" true) foo=@data}}{{!comment}}{{> bar }} {{/foo}}'));
});
it('should traverse to stubs', function() {
var visitor = new Handlebars.Visitor();
visitor.StringLiteral = function(string) {
equal(string.value, '2');
};
visitor.NumberLiteral = function(number) {
equal(number.value, 1);
};
visitor.BooleanLiteral = function(bool) {
equal(bool.value, true);
equal(this.parents.length, 3);
equal(this.parents[0].type, 'SubExpression');
equal(this.parents[1].type, 'BlockStatement');
equal(this.parents[2].type, 'Program');
};
visitor.PathExpression = function(id) {
equal(/(foo\.)?bar$/.test(id.original), true);
};
visitor.ContentStatement = function(content) {
equal(content.value, ' ');
};
visitor.CommentStatement = function(comment) {
equal(comment.value, 'comment');
};
visitor.accept(Handlebars.parse('{{#foo.bar (foo.bar 1 "2" true) foo=@foo.bar}}{{!comment}}{{> bar }} {{/foo.bar}}'));
});
it('should return undefined');
describe('mutating', function() {
describe('fields', function() {
it('should replace value', function() {
var visitor = new Handlebars.Visitor();
visitor.mutating = true;
visitor.StringLiteral = function(string) {
return new Handlebars.AST.NumberLiteral(42, string.locInfo);
};
var ast = Handlebars.parse('{{foo foo="foo"}}');
visitor.accept(ast);
equals(Handlebars.print(ast), '{{ PATH:foo [] HASH{foo=NUMBER{42}} }}\n');
});
it('should treat undefined resonse as identity', function() {
var visitor = new Handlebars.Visitor();
visitor.mutating = true;
var ast = Handlebars.parse('{{foo foo=42}}');
visitor.accept(ast);
equals(Handlebars.print(ast), '{{ PATH:foo [] HASH{foo=NUMBER{42}} }}\n');
});
it('should remove false responses', function() {
var visitor = new Handlebars.Visitor();
visitor.mutating = true;
visitor.Hash = function() {
return false;
};
var ast = Handlebars.parse('{{foo foo=42}}');
visitor.accept(ast);
equals(Handlebars.print(ast), '{{ PATH:foo [] }}\n');
});
it('should throw when removing required values', function() {
shouldThrow(function() {
var visitor = new Handlebars.Visitor();
visitor.mutating = true;
visitor.PathExpression = function() {
return false;
};
var ast = Handlebars.parse('{{foo 42}}');
visitor.accept(ast);
}, Handlebars.Exception, 'MustacheStatement requires path');
});
it('should throw when returning non-node responses', function() {
shouldThrow(function() {
var visitor = new Handlebars.Visitor();
visitor.mutating = true;
visitor.PathExpression = function() {
return {};
};
var ast = Handlebars.parse('{{foo 42}}');
visitor.accept(ast);
}, Handlebars.Exception, 'Unexpected node type "undefined" found when accepting path on MustacheStatement');
});
});
describe('arrays', function() {
it('should replace value', function() {
var visitor = new Handlebars.Visitor();
visitor.mutating = true;
visitor.StringLiteral = function(string) {
return new Handlebars.AST.NumberLiteral(42, string.locInfo);
};
var ast = Handlebars.parse('{{foo "foo"}}');
visitor.accept(ast);
equals(Handlebars.print(ast), '{{ PATH:foo [NUMBER{42}] }}\n');
});
it('should treat undefined resonse as identity', function() {
var visitor = new Handlebars.Visitor();
visitor.mutating = true;
var ast = Handlebars.parse('{{foo 42}}');
visitor.accept(ast);
equals(Handlebars.print(ast), '{{ PATH:foo [NUMBER{42}] }}\n');
});
it('should remove false responses', function() {
var visitor = new Handlebars.Visitor();
visitor.mutating = true;
visitor.NumberLiteral = function() {
return false;
};
var ast = Handlebars.parse('{{foo 42}}');
visitor.accept(ast);
equals(Handlebars.print(ast), '{{ PATH:foo [] }}\n');
});
});
});
});
+17
View File
@@ -1,3 +1,5 @@
/*global shouldCompileTo, shouldCompileToWithPartials */
describe('whitespace control', function() {
it('should strip whitespace around mustache calls', function() {
var hash = {foo: 'bar<'};
@@ -8,6 +10,8 @@ describe('whitespace control', function() {
shouldCompileTo(' {{~&foo~}} ', hash, 'bar<');
shouldCompileTo(' {{~{foo}~}} ', hash, 'bar<');
shouldCompileTo('1\n{{foo~}} \n\n 23\n{{bar}}4', {}, '1\n23\n4');
});
describe('blocks', function() {
@@ -18,6 +22,9 @@ describe('whitespace control', function() {
shouldCompileTo(' {{#if foo~}} bar {{/if~}} ', hash, ' bar ');
shouldCompileTo(' {{~#if foo}} bar {{~/if}} ', hash, ' bar ');
shouldCompileTo(' {{#if foo}} bar {{/if}} ', hash, ' bar ');
shouldCompileTo(' \n\n{{~#if foo~}} \n\nbar \n\n{{~/if~}}\n\n ', hash, 'bar');
shouldCompileTo(' a\n\n{{~#if foo~}} \n\nbar \n\n{{~/if~}}\n\na ', hash, ' abara ');
});
it('should strip whitespace around inverse block calls', function() {
var hash = {};
@@ -26,6 +33,8 @@ describe('whitespace control', function() {
shouldCompileTo(' {{^if foo~}} bar {{/if~}} ', hash, ' bar ');
shouldCompileTo(' {{~^if foo}} bar {{~/if}} ', hash, ' bar ');
shouldCompileTo(' {{^if foo}} bar {{/if}} ', hash, ' bar ');
shouldCompileTo(' \n\n{{~^if foo~}} \n\nbar \n\n{{~/if~}}\n\n ', hash, 'bar');
});
it('should strip whitespace around complex block calls', function() {
var hash = {foo: 'bar<'};
@@ -37,6 +46,9 @@ describe('whitespace control', function() {
shouldCompileTo('{{#if foo~}} bar {{~else~}} baz {{~/if}}', hash, 'bar');
shouldCompileTo('\n\n{{~#if foo~}} \n\nbar \n\n{{~^~}} \n\nbaz \n\n{{~/if~}}\n\n', hash, 'bar');
shouldCompileTo('\n\n{{~#if foo~}} \n\n{{{foo}}} \n\n{{~^~}} \n\nbaz \n\n{{~/if~}}\n\n', hash, 'bar<');
hash = {};
shouldCompileTo('{{#if foo~}} bar {{~^~}} baz {{~/if}}', hash, 'baz');
@@ -45,6 +57,8 @@ describe('whitespace control', function() {
shouldCompileTo('{{#if foo~}} bar {{~^}} baz {{/if}}', hash, ' baz ');
shouldCompileTo('{{#if foo~}} bar {{~else~}} baz {{~/if}}', hash, 'baz');
shouldCompileTo('\n\n{{~#if foo~}} \n\nbar \n\n{{~^~}} \n\nbaz \n\n{{~/if~}}\n\n', hash, 'baz');
});
});
@@ -52,6 +66,9 @@ describe('whitespace control', function() {
shouldCompileToWithPartials('foo {{~> dude~}} ', [{}, {}, {dude: 'bar'}], true, 'foobar');
shouldCompileToWithPartials('foo {{> dude~}} ', [{}, {}, {dude: 'bar'}], true, 'foo bar');
shouldCompileToWithPartials('foo {{> dude}} ', [{}, {}, {dude: 'bar'}], true, 'foo bar ');
shouldCompileToWithPartials('foo\n {{~> dude}} ', [{}, {}, {dude: 'bar'}], true, 'foobar');
shouldCompileToWithPartials('foo\n {{> dude}} ', [{}, {}, {dude: 'bar'}], true, 'foo\n bar');
});
it('should only strip whitespace once', function() {
+43 -13
View File
@@ -1,5 +1,5 @@
%x mu emu com
%x mu emu com raw
%{
@@ -12,8 +12,8 @@ function strip(start, end) {
LEFT_STRIP "~"
RIGHT_STRIP "~"
LOOKAHEAD [=~}\s\/.]
LITERAL_LOOKAHEAD [~}\s]
LOOKAHEAD [=~}\s\/.)|]
LITERAL_LOOKAHEAD [~}\s)]
/*
ID is the inverse of control characters.
@@ -28,7 +28,7 @@ ID [^\s!"#%-,\.\/;->@\[-\^`\{-~]+/{LOOKAHEAD}
%%
[^\x00]*?/("{{") {
[^\x00]*?/("{{") {
if(yytext.slice(-2) === "\\\\") {
strip(0,1);
this.begin("mu");
@@ -43,30 +43,58 @@ ID [^\s!"#%-,\.\/;->@\[-\^`\{-~]+/{LOOKAHEAD}
[^\x00]+ return 'CONTENT';
<emu>[^\x00]{2,}?/("{{"|<<EOF>>) {
if(yytext.slice(-1) !== "\\") this.popState();
if(yytext.slice(-1) === "\\") strip(0,1);
// marks CONTENT up to the next mustache or escaped mustache
<emu>[^\x00]{2,}?/("{{"|"\\{{"|"\\\\{{"|<<EOF>>) {
this.popState();
return 'CONTENT';
}
<com>[\s\S]*?"--}}" strip(0,4); this.popState(); return 'COMMENT';
<raw>"{{{{/"[^\s!"#%-,\.\/;->@\[-\^`\{-~]+/[=}\s\/.]"}}}}" {
yytext = yytext.substr(5, yyleng-9);
this.popState();
return 'END_RAW_BLOCK';
}
<raw>[^\x00]*?/("{{{{/") { return 'CONTENT'; }
<com>[\s\S]*?"--"{RIGHT_STRIP}?"}}" {
this.popState();
return 'COMMENT';
}
<mu>"(" return 'OPEN_SEXPR';
<mu>")" return 'CLOSE_SEXPR';
<mu>"{{{{" { return 'OPEN_RAW_BLOCK'; }
<mu>"}}}}" {
this.popState();
this.begin('raw');
return 'CLOSE_RAW_BLOCK';
}
<mu>"{{"{LEFT_STRIP}?">" return 'OPEN_PARTIAL';
<mu>"{{"{LEFT_STRIP}?"#" return 'OPEN_BLOCK';
<mu>"{{"{LEFT_STRIP}?"/" return 'OPEN_ENDBLOCK';
<mu>"{{"{LEFT_STRIP}?"^"\s*{RIGHT_STRIP}?"}}" this.popState(); return 'INVERSE';
<mu>"{{"{LEFT_STRIP}?\s*"else"\s*{RIGHT_STRIP}?"}}" this.popState(); return 'INVERSE';
<mu>"{{"{LEFT_STRIP}?"^" return 'OPEN_INVERSE';
<mu>"{{"{LEFT_STRIP}?\s*"else" return 'OPEN_INVERSE';
<mu>"{{"{LEFT_STRIP}?\s*"else" return 'OPEN_INVERSE_CHAIN';
<mu>"{{"{LEFT_STRIP}?"{" return 'OPEN_UNESCAPED';
<mu>"{{"{LEFT_STRIP}?"&" return 'OPEN';
<mu>"{{!--" this.popState(); this.begin('com');
<mu>"{{!"[\s\S]*?"}}" strip(3,5); this.popState(); return 'COMMENT';
<mu>"{{"{LEFT_STRIP}?"!--" {
this.unput(yytext);
this.popState();
this.begin('com');
}
<mu>"{{"{LEFT_STRIP}?"!"[\s\S]*?"}}" {
this.popState();
return 'COMMENT';
}
<mu>"{{"{LEFT_STRIP}? return 'OPEN';
<mu>"=" return 'EQUALS';
<mu>".." return 'ID';
<mu>"."/{LOOKAHEAD} return 'ID';
<mu>[\/.] return 'SEP';
<mu>\s+ /*ignore whitespace*/
<mu>\s+ // ignore whitespace
<mu>"}"{RIGHT_STRIP}?"}}" this.popState(); return 'CLOSE_UNESCAPED';
<mu>{RIGHT_STRIP}?"}}" this.popState(); return 'CLOSE';
<mu>'"'("\\"["]|[^"])*'"' yytext = strip(1,2).replace(/\\"/g,'"'); return 'STRING';
@@ -74,7 +102,9 @@ ID [^\s!"#%-,\.\/;->@\[-\^`\{-~]+/{LOOKAHEAD}
<mu>"@" return 'DATA';
<mu>"true"/{LITERAL_LOOKAHEAD} return 'BOOLEAN';
<mu>"false"/{LITERAL_LOOKAHEAD} return 'BOOLEAN';
<mu>\-?[0-9]+/{LITERAL_LOOKAHEAD} return 'INTEGER';
<mu>\-?[0-9]+(?:\.[0-9]+)?/{LITERAL_LOOKAHEAD} return 'NUMBER';
<mu>"as"\s+"|" return 'OPEN_BLOCK_PARAMS';
<mu>"|" return 'CLOSE_BLOCK_PARAMS';
<mu>{ID} return 'ID';
+73 -57
View File
@@ -2,111 +2,127 @@
%ebnf
%{
function stripFlags(open, close) {
return {
left: open[2] === '~',
right: close[0] === '~' || close[1] === '~'
};
}
%}
%%
root
: statements EOF { return new yy.ProgramNode($1); }
: program EOF { return $1; }
;
program
: simpleInverse statements -> new yy.ProgramNode([], $1, $2)
| statements simpleInverse statements -> new yy.ProgramNode($1, $2, $3)
| statements simpleInverse -> new yy.ProgramNode($1, $2, [])
| statements -> new yy.ProgramNode($1)
| simpleInverse -> new yy.ProgramNode([])
| "" -> new yy.ProgramNode([])
;
statements
: statement -> [$1]
| statements statement { $1.push($2); $$ = $1; }
: statement* -> new yy.Program($1, null, {}, yy.locInfo(@$))
;
statement
: openInverse program closeBlock -> new yy.BlockNode($1, $2.inverse, $2, $3)
| openBlock program closeBlock -> new yy.BlockNode($1, $2, $2.inverse, $3)
| mustache -> $1
: mustache -> $1
| block -> $1
| rawBlock -> $1
| partial -> $1
| CONTENT -> new yy.ContentNode($1)
| COMMENT -> new yy.CommentNode($1)
| content -> $1
| COMMENT -> new yy.CommentStatement(yy.stripComment($1), yy.stripFlags($1, $1), yy.locInfo(@$))
;
content
: CONTENT -> new yy.ContentStatement($1, yy.locInfo(@$))
;
rawBlock
: openRawBlock content END_RAW_BLOCK -> yy.prepareRawBlock($1, $2, $3, @$)
;
openRawBlock
: OPEN_RAW_BLOCK helperName param* hash? CLOSE_RAW_BLOCK -> { path: $2, params: $3, hash: $4 }
;
block
: openBlock program inverseChain? closeBlock -> yy.prepareBlock($1, $2, $3, $4, false, @$)
| openInverse program inverseAndProgram? closeBlock -> yy.prepareBlock($1, $2, $3, $4, true, @$)
;
openBlock
: OPEN_BLOCK inMustache CLOSE -> new yy.MustacheNode($2[0], $2[1], $1, stripFlags($1, $3))
: OPEN_BLOCK helperName param* hash? blockParams? CLOSE -> { path: $2, params: $3, hash: $4, blockParams: $5, strip: yy.stripFlags($1, $6) }
;
openInverse
: OPEN_INVERSE inMustache CLOSE -> new yy.MustacheNode($2[0], $2[1], $1, stripFlags($1, $3))
: OPEN_INVERSE helperName param* hash? blockParams? CLOSE -> { path: $2, params: $3, hash: $4, blockParams: $5, strip: yy.stripFlags($1, $6) }
;
openInverseChain
: OPEN_INVERSE_CHAIN helperName param* hash? blockParams? CLOSE -> { path: $2, params: $3, hash: $4, blockParams: $5, strip: yy.stripFlags($1, $6) }
;
inverseAndProgram
: INVERSE program -> { strip: yy.stripFlags($1, $1), program: $2 }
;
inverseChain
: openInverseChain program inverseChain? {
var inverse = yy.prepareBlock($1, $2, $3, $3, false, @$),
program = new yy.Program([inverse], null, {}, yy.locInfo(@$));
program.chained = true;
$$ = { strip: $1.strip, program: program, chain: true };
}
| inverseAndProgram -> $1
;
closeBlock
: OPEN_ENDBLOCK path CLOSE -> {path: $2, strip: stripFlags($1, $3)}
: OPEN_ENDBLOCK helperName CLOSE -> {path: $2, strip: yy.stripFlags($1, $3)}
;
mustache
// Parsing out the '&' escape token at AST level saves ~500 bytes after min due to the removal of one parser node.
// This also allows for handler unification as all mustache node instances can utilize the same handler
: OPEN inMustache CLOSE -> new yy.MustacheNode($2[0], $2[1], $1, stripFlags($1, $3))
| OPEN_UNESCAPED inMustache CLOSE_UNESCAPED -> new yy.MustacheNode($2[0], $2[1], $1, stripFlags($1, $3))
: OPEN helperName param* hash? CLOSE -> yy.prepareMustache($2, $3, $4, $1, yy.stripFlags($1, $5), @$)
| OPEN_UNESCAPED helperName param* hash? CLOSE_UNESCAPED -> yy.prepareMustache($2, $3, $4, $1, yy.stripFlags($1, $5), @$)
;
partial
: OPEN_PARTIAL partialName path? CLOSE -> new yy.PartialNode($2, $3, stripFlags($1, $4))
;
simpleInverse
: OPEN_INVERSE CLOSE -> stripFlags($1, $2)
;
inMustache
: path param* hash? -> [[$1].concat($2), $3]
| dataName -> [[$1], null]
: OPEN_PARTIAL partialName param* hash? CLOSE -> new yy.PartialStatement($2, $3, $4, yy.stripFlags($1, $5), yy.locInfo(@$))
;
param
: path -> $1
| STRING -> new yy.StringNode($1)
| INTEGER -> new yy.IntegerNode($1)
| BOOLEAN -> new yy.BooleanNode($1)
| dataName -> $1
: helperName -> $1
| sexpr -> $1
;
sexpr
: OPEN_SEXPR helperName param* hash? CLOSE_SEXPR -> new yy.SubExpression($2, $3, $4, yy.locInfo(@$))
;
hash
: hashSegment+ -> new yy.HashNode($1)
: hashSegment+ -> new yy.Hash($1, yy.locInfo(@$))
;
hashSegment
: ID EQUALS param -> [$1, $3]
: ID EQUALS param -> new yy.HashPair($1, $3, yy.locInfo(@$))
;
blockParams
: OPEN_BLOCK_PARAMS ID+ CLOSE_BLOCK_PARAMS -> $2
;
helperName
: path -> $1
| dataName -> $1
| STRING -> new yy.StringLiteral($1, yy.locInfo(@$))
| NUMBER -> new yy.NumberLiteral($1, yy.locInfo(@$))
| BOOLEAN -> new yy.BooleanLiteral($1, yy.locInfo(@$))
;
partialName
: path -> new yy.PartialNameNode($1)
| STRING -> new yy.PartialNameNode(new yy.StringNode($1))
| INTEGER -> new yy.PartialNameNode(new yy.IntegerNode($1))
: helperName -> $1
| sexpr -> $1
;
dataName
: DATA path -> new yy.DataNode($2)
: DATA pathSegments -> yy.preparePath(true, $2, @$)
;
path
: pathSegments -> new yy.IdNode($1)
: pathSegments -> yy.preparePath(false, $1, @$)
;
pathSegments
: pathSegments SEP ID { $1.push({part: $3, separator: $2}); $$ = $1; }
| ID -> [{part: $1}]
;
+2
View File
@@ -0,0 +1,2 @@
/* jshint ignore:start */
/* istanbul ignore next */
+1
View File
@@ -1 +1,2 @@
export default handlebars;
/* jshint ignore:end */
-13
View File
@@ -1,13 +0,0 @@
module.exports = function(grunt) {
grunt.registerMultiTask('packager', 'Transpiles scripts written using ES6 to ES5.', function() {
// Execute in here to prevent traceur private var blowup
var Packager = require('es6-module-packager').default,
fs = require('fs');
var options = this.options();
this.files.forEach(function(file) {
var packager = new Packager(file.src[0], {export: options.export});
fs.writeFileSync(file.dest, packager.toLocals());
});
});
};
+8 -2
View File
@@ -4,7 +4,13 @@ module.exports = function(grunt) {
grunt.registerTask('parser', 'Generate jison parser.', function() {
var done = this.async();
var child = childProcess.spawn('./node_modules/.bin/jison', ['-m', 'js', 'src/handlebars.yy', 'src/handlebars.l'], {stdio: 'inherit'});
var cmd = './node_modules/.bin/jison';
if(process.platform === 'win32'){
cmd = 'node_modules\\.bin\\jison.cmd';
}
var child = childProcess.spawn(cmd, ['-m', 'js', 'src/handlebars.yy', 'src/handlebars.l'], {stdio: 'inherit'});
child.on('exit', function(code) {
if (code != 0) {
grunt.fatal('Jison failure: ' + code);
@@ -12,7 +18,7 @@ module.exports = function(grunt) {
return;
}
var src = ['handlebars.js', 'src/parser-suffix.js'].map(grunt.file.read).join('');
var src = ['src/parser-prefix.js', 'handlebars.js', 'src/parser-suffix.js'].map(grunt.file.read).join('');
grunt.file.delete('handlebars.js');
grunt.file.write('lib/handlebars/compiler/parser.js', src);
+44
View File
@@ -0,0 +1,44 @@
var childProcess = require('child_process'),
fs = require('fs');
module.exports = function(grunt) {
grunt.registerTask('test:bin', function() {
var done = this.async();
childProcess.exec('./bin/handlebars -a spec/artifacts/empty.handlebars', function(err, stdout) {
if (err) {
throw err;
}
var expected = fs.readFileSync('./spec/expected/empty.amd.js');
if (stdout.toString() !== expected.toString()) {
throw new Error('Expected binary output differed:\n\n"' + stdout + '"\n\n"' + expected + '"');
}
done();
});
});
grunt.registerTask('test:mocha', function() {
var done = this.async();
var runner = childProcess.fork('./spec/env/runner', [], {stdio: 'inherit'});
runner.on('close', function(code) {
if (code != 0) {
grunt.fatal(code + ' tests failed');
}
done();
});
});
grunt.registerTask('test:cov', function() {
var done = this.async();
var runner = childProcess.fork('node_modules/.bin/istanbul', ['cover', '--', './spec/env/runner.js'], {stdio: 'inherit'});
runner.on('close', function(code) {
if (code != 0) {
grunt.fatal(code + ' tests failed');
}
done();
});
});
grunt.registerTask('test', ['test:bin', 'test:cov']);
};
+11 -4
View File
@@ -80,20 +80,27 @@ module.exports = {
childProcess.exec('git tag -a --message=' + name + ' ' + name, {}, function(err, stdout, stderr) {
if (err) {
throw new Error('git.tag: ' + err.message);
throw err;
}
callback();
});
},
tagName: function(callback) {
childProcess.exec('git tag -l --points-at HEAD', {}, function(err, stdout) {
childProcess.exec('git describe --tags', {}, function(err, stdout) {
if (err) {
throw new Error('git.tagName: ' + err.message);
}
var tags = stdout.trim().split(/\n/),
versionTags = tags.filter(function(tag) { return /^v/.test(tag); });
var tags = stdout.trim().split(/\n/);
tags = tags.filter(function(info) {
info = info.split('-');
return info.length == 1;
});
var versionTags = tags.filter(function(info) {
return /^v/.test(info[0]);
});
callback(undefined, versionTags[0] || tags[0]);
});
}