pax_global_header 0000666 0000000 0000000 00000000064 13372117050 0014511 g ustar 00root root 0000000 0000000 52 comment=38b1448e65f1d4716c3e3ad792ae6ab3aaf487ab
mustache.js-3.0.1/ 0000775 0000000 0000000 00000000000 13372117050 0013736 5 ustar 00root root 0000000 0000000 mustache.js-3.0.1/.eslintrc 0000664 0000000 0000000 00000000564 13372117050 0015567 0 ustar 00root root 0000000 0000000 {
"env": {
"browser": true,
"node": true
},
"rules": {
"func-names": 2,
"no-mixed-spaces-and-tabs": 2,
"quotes": [2, "single", "avoid-escape"],
"semi": 2,
"keyword-spacing": 2,
"space-before-function-paren": 2,
"curly": 0,
"consistent-return": 0,
"no-use-before-define": 0,
"no-process-exit": 0,
"strict": 0
}
} mustache.js-3.0.1/.gitignore 0000664 0000000 0000000 00000000232 13372117050 0015723 0 ustar 00root root 0000000 0000000 node_modules
jquery.mustache.js
mootools.mustache.js
dojox
yui3
qooxdoo.mustache.js
test/render-test-browser.js
npm-debug.log
test/render-test-browser.js mustache.js-3.0.1/.gitmodules 0000664 0000000 0000000 00000000122 13372117050 0016106 0 ustar 00root root 0000000 0000000 [submodule "test/spec"]
path = test/spec
url = https://github.com/mustache/spec
mustache.js-3.0.1/.travis.yml 0000664 0000000 0000000 00000001223 13372117050 0016045 0 ustar 00root root 0000000 0000000 language: node_js
node_js:
- 0.8
- '0.10'
- 0.12
- 4
- 6
before_install:
- "test $TRAVIS_NODE_VERSION != '0.8' || npm install -g npm@2.x"
script:
- npm test
- "test $TRAVIS_PULL_REQUEST != 'false' || test $TRAVIS_NODE_VERSION != '6' || npm run test-browser"
env:
global:
- secure: L0dg0jr2fwkc2tPwP5svybILPBn2qdLzMrWc5tEXg3MPcy8D59Gvf+ri7INqo+ETPM20o5CsaDCH+LHUNS/V0G4VG1ajvsy7d8uh3hnb/K6VfVui/CjsHIqOcOZrbxVxgyX+iMXEXAj0+Syow9uDQHVhrz1qqad1n79likNCXa4=
- secure: J4vbGKivULEHWRWExAWDLkFk9EDU7E6Ny+iRc/oKxXHnBYn9oL2Hfc1J92fOttaFtUzpz7r5FaNa3DGlyAI0wimq5GY8KJQGcquoskerXucd8iJbLCs3nxDeShl4UwHpDIXF8xbH/rUIkrGSKnktf0McMRIyeN95hzug0nxOwAw=
mustache.js-3.0.1/.zuul.yml 0000664 0000000 0000000 00000000276 13372117050 0015543 0 ustar 00root root 0000000 0000000 ui: mocha-bdd
browsers:
- name: chrome
version: latest
- name: firefox
version: latest
- name: ie
version: 9..latest
concurrency: 1
tunnel:
type: ngrok
bind_tls: false
mustache.js-3.0.1/CHANGELOG.md 0000664 0000000 0000000 00000036743 13372117050 0015564 0 ustar 00root root 0000000 0000000 # Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [3.0.1] / 11 November 2018
* [#679]: Fix partials not rendering tokens when using custom tags, by [@stackchain].
## [3.0.0] / 16 September 2018
We are very happy to announce a new major version of mustache.js. We want to be very careful not to break projects
out in the wild, and adhering to [Semantic Versioning](http://semver.org/) we have therefore cut this new major version.
The changes introduced will likely not require any actions for most using projects. The things to look out for that
might cause unexpected rendering results are described in the migration guide below.
A big shout out and thanks to [@raymond-lam] for this release! Without his contributions with code and issue triaging,
this release would never have happened.
### Major
* [#618]: Allow rendering properties of primitive types that are not objects, by [@raymond-lam].
* [#643]: `Writer.prototype.parse` to cache by tags in addition to template string, by [@raymond-lam].
* [#664]: Fix `Writer.prototype.parse` cache, by [@seminaoki].
### Minor
* [#673]: Add `tags` parameter to `Mustache.render()`, by [@raymond-lam].
### Migrating from mustache.js v2.x to v3.x
#### Rendering properties of primitive types
We have ensured properties of primitive types can be rendered at all times. That means `Array.length`, `String.length`
and similar. A corner case where this could cause unexpected output follows:
View:
```
{
stooges: [
{ name: "Moe" },
{ name: "Larry" },
{ name: "Curly" }
]
}
```
Template:
```
{{#stooges}}
{{name}}: {{name.length}} characters
{{/stooges}}
```
Output with v3.0:
```
Moe: 3 characters
Larry: 5 characters
Curly: 5 characters
```
Output with v2.x:
```
Moe: characters
Larry: characters
Curly: characters
```
#### Caching for templates with custom delimiters
We have improved the templates cache to ensure custom delimiters are taken into consideration for the cache.
This improvement might cause unexpected rendering behaviour for using projects actively using the custom delimiters functionality.
Previously it was possible to use `Mustache.parse()` as a means to set global custom delimiters. If custom
delimiters were provided as an argument, it would affect all following calls to `Mustache.render()`.
Consider the following:
```js
const template = "[[item.title]] [[item.value]]";
mustache.parse(template, ["[[", "]]"]);
console.log(
mustache.render(template, {
item: {
title: "TEST",
value: 1
}
})
);
>> TEST 1
```
The above illustrates the fact that `Mustache.parse()` made mustache.js cache the template without considering
the custom delimiters provided. This is no longer true.
We no longer encourage using `Mustache.parse()` for this purpose, but have rather added a fourth argument to
`Mustache.render()` letting you provide custom delimiters when rendering.
If you still need the pre-parse the template and use custom delimiters at the same time, ensure to provide
the custom delimiters as argument to `Mustache.render()` as well.
## [2.3.2] / 17 August 2018
This release is made to revert changes introduced in [2.3.1] that caused unexpected behaviour for several users.
### Minor
* [#670]: Rollback template cache causing unexpected behaviour, by [@raymond-lam].
## [2.3.1] / 7 August 2018
### Minor
* [#643]: `Writer.prototype.parse` to cache by tags in addition to template string, by [@raymond-lam].
* [#664]: Fix `Writer.prototype.parse` cache, by [@seminaoki].
### Dev
* [#666]: Install release tools with npm rather than pre-commit hook & `Rakefile`, by [@phillipj].
* [#667], [#668]: Stabilize browser test suite, by [@phillipj].
### Docs
* [#644]: Document global Mustache.escape overriding capacity, by [@paultopia].
* [#657]: Correct `Mustache.parse()` return type documentation, by [@bbrooks].
## [2.3.0] / 8 November 2016
### Minor
* [#540]: Add optional `output` argument to mustache CLI, by [@wizawu].
* [#597]: Add compatibility with amdclean, by [@mightyplow].
### Dev
* [#553]: Assert `null` lookup when rendering an unescaped value, by [@dasilvacontin].
* [#580], [#610]: Ignore eslint for greenkeeper updates, by [@phillipj].
* [#560]: Fix CLI tests for Windows, by [@kookookchoozeus].
* Run browser tests w/node v4, by [@phillipj].
### Docs
* [#542]: Add API documentation to README, by [@tomekwi].
* [#546]: Add missing syntax highlighting to README code blocks, by [@pra85].
* [#569]: Update Ctemplate links in README, by [@mortonfox].
* [#592]: Change "loadUser" to "loadUser()" in README, by [@Flaque].
* [#593]: Adding doctype to HTML code example in README, by [@calvinf].
### Dependencies
* eslint -> 2.2.0. Breaking changes fix by [@phillipj]. [#548]
* eslint -> 2.5.1.
* mocha -> 3.0.2.
* zuul -> 3.11.0.
## [2.2.1] / 13 December 2015
### Fixes
* Improve HTML escaping, by [@phillipj].
* Fix inconsistency in defining global mustache object, by [@simast].
* Fix switch-case indent error, by [@norfish].
* Unpin chai and eslint versions, by [@dasilvacontin].
* Update README.md with proper grammar, by [@EvanLovely].
* Update mjackson username in README, by [@mjackson].
* Remove syntax highlighting in README code sample, by [@imagentleman].
* Fix typo in README, by [@Xcrucifier].
* Fix link typo in README, by [@keirog].
## [2.2.0] / 15 October 2015
### Added
* Add Partials support to CLI, by [@palkan].
### Changed
* Move install instructions to README's top, by [@mateusortiz]
* Improved devhook install output, by [@ShashankaNataraj].
* Clarifies and improves language in documentation, by [@jfmercer].
* Linting CLI tool, by [@phillipj].
* npm 2.x and node v4 on Travis, by [@phillipj].
### Fixes
* Fix README spelling error to "aforementioned", by [@djchie].
* Equal error message test in .render() for server and browser, by [@phillipj].
### Dependencies
* chai -> 3.3.0
* eslint -> 1.6.0
## [2.1.3] / 23 July 2015
### Added
* Throw error when providing .render() with invalid template type, by [@phillipj].
* Documents use of string literals containing double quotes, by [@jfmercer].
### Changed
* Move mustache gif to githubusercontent, by [@Andersos].
### Fixed
* Update UMD Shim to be resilient to HTMLElement global pollution, by [@mikesherov].
## [2.1.2] / 17 June 2015
### Added
* Mustache global definition ([#466]) by [@yousefcisco].
## [2.1.1] / 11 June 2015
### Added
* State that we use semver on the change log, by [@dasilvacontin].
* Added version links to change log, by [@dasilvacontin].
### Fixed
* Bugfix for using values from view's context prototype, by [@phillipj].
* Improve test with undefined/null lookup hit using dot notation, by [@dasilvacontin].
* Bugfix for null/undefined lookup hit when using dot notation, by [@phillipj].
* Remove moot `version` property from bower.json, by [@kkirsche].
* bower.json doesn't require a version bump via hook, by [@dasilvacontin].
## [2.1.0] / 5 June 2015
* Added license attribute to package.json, by [@pgilad].
* Minor changes to make mustache.js compatible with both WSH and ASP, by [@nagaozen].
* Improve CLI view parsing error, by [@phillipj].
* Bugfix for view context cache, by [@phillipj].
## [2.0.0] / 27 Mar 2015
* Fixed lookup not stopping upon finding `undefined` or `null` values, by [@dasilvacontin].
* Refactored pre-commit hook, by [@dasilvacontin].
## [1.2.0] / 24 Mar 2015
* Added -v option to CLI, by [@phillipj].
* Bugfix for rendering Number when it serves as the Context, by [@phillipj].
* Specified files in package.json for a cleaner install, by [@phillipj].
## [1.1.0] / 18 Feb 2015
* Refactor Writer.renderTokens() for better readability, by [@phillipj].
* Cleanup tests section in readme, by [@phillipj].
* Added JSHint to tests/CI, by [@phillipj].
* Added node v0.12 on travis, by [@phillipj].
* Created command line tool, by [@phillipj].
* Added *falsy* to Inverted Sections description in README, by [@kristijanmatic].
## [1.0.0] / 20 Dec 2014
* Inline tag compilation, by [@mjackson].
* Fixed AMD registration, volo package.json entry, by [@jrburke].
* Added spm support, by [@afc163].
* Only access properties of objects on Context.lookup, by [@cmbuckley].
## [0.8.2] / 17 Mar 2014
* Supporting Bower through a bower.json file.
## [0.8.1] / 3 Jan 2014
* Fix usage of partial templates.
## [0.8.0] / 2 Dec 2013
* Remove compile* writer functions, use mustache.parse instead. Smaller API.
* Throw an error when rendering a template that contains higher-order sections and
the original template is not provided.
* Remove low-level Context.make function.
* Better code readability and inline documentation.
* Stop caching templates by name.
## [0.7.3] / 5 Nov 2013
* Don't require the original template to be passed to the rendering function
when using compiled templates. This is still required when using higher-order
functions in order to be able to extract the portion of the template
that was contained by that section. Fixes [#262].
* Performance improvements.
## [0.7.2] / 27 Dec 2012
* Fixed a rendering bug ([#274]) when using nested higher-order sections.
* Better error reporting on failed parse.
* Converted tests to use mocha instead of vows.
## [0.7.1] / 6 Dec 2012
* Handle empty templates gracefully. Fixes [#265], [#267], and [#270].
* Cache partials by template, not by name. Fixes [#257].
* Added Mustache.compileTokens to compile the output of Mustache.parse. Fixes
[#258].
## [0.7.0] / 10 Sep 2012
* Rename Renderer => Writer.
* Allow partials to be loaded dynamically using a callback (thanks
[@TiddoLangerak] for the suggestion).
* Fixed a bug with higher-order sections that prevented them from being
passed the raw text of the section from the original template.
* More concise token format. Tokens also include start/end indices in the
original template.
* High-level API is consistent with the Writer API.
* Allow partials to be passed to the pre-compiled function (thanks
[@fallenice]).
* Don't use eval (thanks [@cweider]).
## [0.6.0] / 31 Aug 2012
* Use JavaScript's definition of falsy when determining whether to render an
inverted section or not. Issue [#186].
* Use Mustache.escape to escape values inside {{}}. This function may be
reassigned to alter the default escaping behavior. Issue [#244].
* Fixed a bug that clashed with QUnit (thanks [@kannix]).
* Added volo support (thanks [@guybedford]).
[3.0.1]: https://github.com/janl/mustache.js/compare/v3.0.0...v3.0.1
[3.0.0]: https://github.com/janl/mustache.js/compare/v2.3.2...v3.0.0
[2.3.2]: https://github.com/janl/mustache.js/compare/v2.3.1...v2.3.2
[2.3.1]: https://github.com/janl/mustache.js/compare/v2.3.0...v2.3.1
[2.3.0]: https://github.com/janl/mustache.js/compare/v2.2.1...v2.3.0
[2.2.1]: https://github.com/janl/mustache.js/compare/v2.2.0...v2.2.1
[2.2.0]: https://github.com/janl/mustache.js/compare/v2.1.3...v2.2.0
[2.1.3]: https://github.com/janl/mustache.js/compare/v2.1.2...v2.1.3
[2.1.2]: https://github.com/janl/mustache.js/compare/v2.1.1...v2.1.2
[2.1.1]: https://github.com/janl/mustache.js/compare/v2.1.0...v2.1.1
[2.1.0]: https://github.com/janl/mustache.js/compare/v2.0.0...v2.1.0
[2.0.0]: https://github.com/janl/mustache.js/compare/v1.2.0...v2.0.0
[1.2.0]: https://github.com/janl/mustache.js/compare/v1.1.0...v1.2.0
[1.1.0]: https://github.com/janl/mustache.js/compare/v1.0.0...v1.1.0
[1.0.0]: https://github.com/janl/mustache.js/compare/0.8.2...v1.0.0
[0.8.2]: https://github.com/janl/mustache.js/compare/0.8.1...0.8.2
[0.8.1]: https://github.com/janl/mustache.js/compare/0.8.0...0.8.1
[0.8.0]: https://github.com/janl/mustache.js/compare/0.7.3...0.8.0
[0.7.3]: https://github.com/janl/mustache.js/compare/0.7.2...0.7.3
[0.7.2]: https://github.com/janl/mustache.js/compare/0.7.1...0.7.2
[0.7.1]: https://github.com/janl/mustache.js/compare/0.7.0...0.7.1
[0.7.0]: https://github.com/janl/mustache.js/compare/0.6.0...0.7.0
[0.6.0]: https://github.com/janl/mustache.js/compare/0.5.2...0.6.0
[#186]: https://github.com/janl/mustache.js/issues/186
[#244]: https://github.com/janl/mustache.js/issues/244
[#257]: https://github.com/janl/mustache.js/issues/257
[#258]: https://github.com/janl/mustache.js/issues/258
[#262]: https://github.com/janl/mustache.js/issues/262
[#265]: https://github.com/janl/mustache.js/issues/265
[#267]: https://github.com/janl/mustache.js/issues/267
[#270]: https://github.com/janl/mustache.js/issues/270
[#274]: https://github.com/janl/mustache.js/issues/274
[#466]: https://github.com/janl/mustache.js/issues/466
[#540]: https://github.com/janl/mustache.js/issues/540
[#542]: https://github.com/janl/mustache.js/issues/542
[#546]: https://github.com/janl/mustache.js/issues/546
[#548]: https://github.com/janl/mustache.js/issues/548
[#553]: https://github.com/janl/mustache.js/issues/553
[#560]: https://github.com/janl/mustache.js/issues/560
[#569]: https://github.com/janl/mustache.js/issues/569
[#580]: https://github.com/janl/mustache.js/issues/580
[#592]: https://github.com/janl/mustache.js/issues/592
[#593]: https://github.com/janl/mustache.js/issues/593
[#597]: https://github.com/janl/mustache.js/issues/597
[#610]: https://github.com/janl/mustache.js/issues/610
[#643]: https://github.com/janl/mustache.js/issues/643
[#644]: https://github.com/janl/mustache.js/issues/644
[#657]: https://github.com/janl/mustache.js/issues/657
[#664]: https://github.com/janl/mustache.js/issues/664
[#666]: https://github.com/janl/mustache.js/issues/666
[#667]: https://github.com/janl/mustache.js/issues/667
[#668]: https://github.com/janl/mustache.js/issues/668
[#670]: https://github.com/janl/mustache.js/issues/670
[#618]: https://github.com/janl/mustache.js/issues/618
[#673]: https://github.com/janl/mustache.js/issues/673
[#679]: https://github.com/janl/mustache.js/issues/679
[@afc163]: https://github.com/afc163
[@Andersos]: https://github.com/Andersos
[@bbrooks]: https://github.com/bbrooks
[@calvinf]: https://github.com/calvinf
[@cmbuckley]: https://github.com/cmbuckley
[@cweider]: https://github.com/cweider
[@dasilvacontin]: https://github.com/dasilvacontin
[@djchie]: https://github.com/djchie
[@EvanLovely]: https://github.com/EvanLovely
[@fallenice]: https://github.com/fallenice
[@Flaque]: https://github.com/Flaque
[@guybedford]: https://github.com/guybedford
[@imagentleman]: https://github.com/imagentleman
[@jfmercer]: https://github.com/jfmercer
[@jrburke]: https://github.com/jrburke
[@kannix]: https://github.com/kannix
[@keirog]: https://github.com/keirog
[@kkirsche]: https://github.com/kkirsche
[@kookookchoozeus]: https://github.com/kookookchoozeus
[@kristijanmatic]: https://github.com/kristijanmatic
[@mateusortiz]: https://github.com/mateusortiz
[@mightyplow]: https://github.com/mightyplow
[@mikesherov]: https://github.com/mikesherov
[@mjackson]: https://github.com/mjackson
[@mortonfox]: https://github.com/mortonfox
[@nagaozen]: https://github.com/nagaozen
[@norfish]: https://github.com/norfish
[@palkan]: https://github.com/palkan
[@paultopia]: https://github.com/paultopia
[@pgilad]: https://github.com/pgilad
[@phillipj]: https://github.com/phillipj
[@pra85]: https://github.com/pra85
[@raymond-lam]: https://github.com/raymond-lam
[@seminaoki]: https://github.com/seminaoki
[@ShashankaNataraj]: https://github.com/ShashankaNataraj
[@simast]: https://github.com/simast
[@stackchain]: https://github.com/stackchain
[@TiddoLangerak]: https://github.com/TiddoLangerak
[@tomekwi]: https://github.com/tomekwi
[@wizawu]: https://github.com/wizawu
[@Xcrucifier]: https://github.com/Xcrucifier
[@yousefcisco]: https://github.com/yousefcisco
mustache.js-3.0.1/LICENSE 0000664 0000000 0000000 00000002237 13372117050 0014747 0 ustar 00root root 0000000 0000000 The MIT License
Copyright (c) 2009 Chris Wanstrath (Ruby)
Copyright (c) 2010-2014 Jan Lehnardt (JavaScript)
Copyright (c) 2010-2015 The mustache.js community
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
mustache.js-3.0.1/MIGRATING.md 0000664 0000000 0000000 00000002473 13372117050 0015607 0 ustar 00root root 0000000 0000000 # Migrating Guide
## Moving to mustache.js v2
### Overview
mustache.js v2 introduces a bug fix that breaks compatibility with older versions: fixing null and undefined lookup.
When mustache.js tries to render a variable `{{name}}`, it executes a `lookup` function to figure out which value it should render. This function looks up the value for the key `name` in the current context, and if there is no such key in the current context it looks up the parent contexts recursively.
Value lookup should stop whenever the key exists in the context. However, due to a bug, this was not happening when the value was `null` or `undefined` even though the key existed in the context.
Here's a simple example of the same template rendered with both mustache.js v1 and v2:
Template:
```mustache
{{#friends}}
{{name}}'s twitter is: {{twitter}}
{{/friends}}
```
View:
```json
{
"name": "David",
"twitter": "@dasilvacontin",
"friends": [
{
"name": "Phillip",
"twitter": "@phillipjohnsen"
},
{
"name": "Jan",
"twitter": null
}
]
}
```
Rendered using mustache.js v1:
```text
Phillip's twitter is: @phillipjohnsen
Jan's twitter is: @dasilvacontin
```
Rendered using mustache.js v2:
```text
Phillip's twitter is: @phillipjohnsen
Jan's twitter is:
``` mustache.js-3.0.1/README.md 0000664 0000000 0000000 00000041052 13372117050 0015217 0 ustar 00root root 0000000 0000000 # mustache.js - Logic-less {{mustache}} templates with JavaScript
> What could be more logical awesome than no logic at all?
[](https://travis-ci.org/janl/mustache.js) [](https://gitter.im/janl/mustache.js)
[mustache.js](http://github.com/janl/mustache.js) is an implementation of the [mustache](http://mustache.github.com/) template system in JavaScript.
[Mustache](http://mustache.github.com/) is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object.
We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values.
For a language-agnostic overview of mustache's template syntax, see the `mustache(5)` [manpage](http://mustache.github.com/mustache.5.html).
## Where to use mustache.js?
You can use mustache.js to render mustache templates anywhere you can use JavaScript. This includes web browsers, server-side environments such as [node](http://nodejs.org/), and [CouchDB](http://couchdb.apache.org/) views.
mustache.js ships with support for both the [CommonJS](http://www.commonjs.org/) module API and the [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) API, or AMD.
And this will be your templates after you use Mustache:

## Install
You can get Mustache via npm.
```bash
$ npm install mustache --save
```
or install with bower:
```bash
$ bower install --save mustache
```
## Command line tool
mustache.js is shipped with a node based command line tool. It might be installed as a global tool on your computer to render a mustache template of some kind
```bash
$ npm install -g mustache
$ mustache dataView.json myTemplate.mustache > output.html
```
also supports stdin.
```bash
$ cat dataView.json | mustache - myTemplate.mustache > output.html
```
or as a package.json `devDependency` in a build process maybe?
```bash
$ npm install mustache --save-dev
```
```json
{
"scripts": {
"build": "mustache dataView.json myTemplate.mustache > public/output.html"
}
}
```
```bash
$ npm run build
```
The command line tool is basically a wrapper around `Mustache.render` so you get all the features.
If your templates use partials you should pass paths to partials using `-p` flag:
```bash
$ mustache -p path/to/partial1.mustache -p path/to/partial2.mustache dataView.json myTemplate.mustache
```
## Who uses mustache.js?
An updated list of mustache.js users is kept [on the Github wiki](http://wiki.github.com/janl/mustache.js/beard-competition). Add yourself or your company if you use mustache.js!
## Contributing
mustache.js is a mature project, but it continues to actively invite maintainers. You can help out a high-profile project that is used in a lot of places on the web. There is [plenty](https://github.com/janl/mustache.js/issues) of [work](https://github.com/janl/mustache.js/pulls) to do. No big commitment required, if all you do is review a single [Pull Request](https://github.com/janl/mustache.js/pulls), you are a maintainer. And a hero.
### Your First Contribution
- review a [Pull Request](https://github.com/janl/mustache.js/pulls)
- fix an [Issue](https://github.com/janl/mustache.js/issues)
- update the [documentation](https://github.com/janl/mustache.js#usage)
- make a website
- write a tutorial
* * *
## Usage
Below is a quick example how to use mustache.js:
```js
var view = {
title: "Joe",
calc: function () {
return 2 + 4;
}
};
var output = Mustache.render("{{title}} spends {{calc}}", view);
```
In this example, the `Mustache.render` function takes two parameters: 1) the [mustache](http://mustache.github.com/) template and 2) a `view` object that contains the data and code needed to render the template.
## API
Following is an [rtype](https://git.io/rtype) signature of the most commonly used functions.
```js
Mustache.render(
template : String,
view : Object,
partials? : Object,
tags = ['{{', '}}'] : Tags,
) => String
Mustache.parse(
template : String,
tags = ['{{', '}}'] : Tags,
) => Token[]
interface Token [String, String, Number, Number, Token[]?, Number?]
interface Tags [String, String]
```
## Templates
A [mustache](http://mustache.github.com/) template is a string that contains any number of mustache tags. Tags are indicated by the double mustaches that surround them. `{{person}}` is a tag, as is `{{#person}}`. In both examples we refer to `person` as the tag's key. There are several types of tags available in mustache.js, described below.
There are several techniques that can be used to load templates and hand them to mustache.js, here are two of them:
#### Include Templates
If you need a template for a dynamic part in a static website, you can consider including the template in the static HTML file to avoid loading templates separately. Here's a small example using `jQuery`:
```html
Loading...
```
```js
function loadUser() {
var template = $('#template').html();
Mustache.parse(template); // optional, speeds up future uses
var rendered = Mustache.render(template, {name: "Luke"});
$('#target').html(rendered);
}
```
#### Load External Templates
If your templates reside in individual files, you can load them asynchronously and render them when they arrive. Another example using `jQuery`:
```js
function loadUser() {
$.get('template.mst', function(template) {
var rendered = Mustache.render(template, {name: "Luke"});
$('#target').html(rendered);
});
}
```
### Variables
The most basic tag type is a simple variable. A `{{name}}` tag renders the value of the `name` key in the current context. If there is no such key, nothing is rendered.
All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: `{{{name}}}`. You can also use `&` to unescape a variable.
If you'd like to change HTML-escaping behavior globally (for example, to template non-HTML formats), you can override Mustache's escape function. For example, to disable all escaping: `Mustache.escape = function(text) {return text;};`.
If you want `{{name}}` _not_ to be interpreted as a mustache tag, but rather to appear exactly as `{{name}}` in the output, you must change and then restore the default delimiter. See the [Custom Delimiters](#custom-delimiters) section for more information.
View:
```json
{
"name": "Chris",
"company": "GitHub"
}
```
Template:
```
* {{name}}
* {{age}}
* {{company}}
* {{{company}}}
* {{&company}}
{{=<% %>=}}
* {{company}}
<%={{ }}=%>
```
Output:
```html
* Chris
*
* <b>GitHub</b>
* GitHub
* GitHub
* {{company}}
```
JavaScript's dot notation may be used to access keys that are properties of objects in a view.
View:
```json
{
"name": {
"first": "Michael",
"last": "Jackson"
},
"age": "RIP"
}
```
Template:
```html
* {{name.first}} {{name.last}}
* {{age}}
```
Output:
```html
* Michael Jackson
* RIP
```
### Sections
Sections render blocks of text one or more times, depending on the value of the key in the current context.
A section begins with a pound and ends with a slash. That is, `{{#person}}` begins a `person` section, while `{{/person}}` ends it. The text between the two tags is referred to as that section's "block".
The behavior of the section is determined by the value of the key.
#### False Values or Empty Lists
If the `person` key does not exist, or exists and has a value of `null`, `undefined`, `false`, `0`, or `NaN`, or is an empty string or an empty list, the block will not be rendered.
View:
```json
{
"person": false
}
```
Template:
```html
Shown.
{{#person}}
Never shown!
{{/person}}
```
Output:
```html
Shown.
```
#### Non-Empty Lists
If the `person` key exists and is not `null`, `undefined`, or `false`, and is not an empty list the block will be rendered one or more times.
When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way we can loop over collections.
View:
```json
{
"stooges": [
{ "name": "Moe" },
{ "name": "Larry" },
{ "name": "Curly" }
]
}
```
Template:
```html
{{#stooges}}
{{name}}
{{/stooges}}
```
Output:
```html
Moe
Larry
Curly
```
When looping over an array of strings, a `.` can be used to refer to the current item in the list.
View:
```json
{
"musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
}
```
Template:
```html
{{#musketeers}}
* {{.}}
{{/musketeers}}
```
Output:
```html
* Athos
* Aramis
* Porthos
* D'Artagnan
```
If the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration.
View:
```js
{
"beatles": [
{ "firstName": "John", "lastName": "Lennon" },
{ "firstName": "Paul", "lastName": "McCartney" },
{ "firstName": "George", "lastName": "Harrison" },
{ "firstName": "Ringo", "lastName": "Starr" }
],
"name": function () {
return this.firstName + " " + this.lastName;
}
}
```
Template:
```html
{{#beatles}}
* {{name}}
{{/beatles}}
```
Output:
```html
* John Lennon
* Paul McCartney
* George Harrison
* Ringo Starr
```
#### Functions
If the value of a section key is a function, it is called with the section's literal block of text, un-rendered, as its first argument. The second argument is a special rendering function that uses the current view as its view argument. It is called in the context of the current view object.
View:
```js
{
"name": "Tater",
"bold": function () {
return function (text, render) {
return "" + render(text) + "";
}
}
}
```
Template:
```html
{{#bold}}Hi {{name}}.{{/bold}}
```
Output:
```html
Hi Tater.
```
### Inverted Sections
An inverted section opens with `{{^section}}` instead of `{{#section}}`. The block of an inverted section is rendered only if the value of that section's tag is `null`, `undefined`, `false`, *falsy* or an empty list.
View:
```json
{
"repos": []
}
```
Template:
```html
{{#repos}}{{name}}{{/repos}}
{{^repos}}No repos :({{/repos}}
```
Output:
```html
No repos :(
```
### Comments
Comments begin with a bang and are ignored. The following template:
```html
Today{{! ignore me }}.
```
Will render as follows:
```html
Today.
```
Comments may contain newlines.
### Partials
Partials begin with a greater than sign, like {{> box}}.
Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops.
They also inherit the calling context. Whereas in ERB you may have this:
```html+erb
<%= partial :next_more, :start => start, :size => size %>
```
Mustache requires only this:
```html
{{> next_more}}
```
Why? Because the `next_more.mustache` file will inherit the `size` and `start` variables from the calling context. In this way you may want to think of partials as includes, imports, template expansion, nested templates, or subtemplates, even though those aren't literally the case here.
For example, this template and partial:
base.mustache:
Names
{{#names}}
{{> user}}
{{/names}}
user.mustache:
{{name}}
Can be thought of as a single, expanded template:
```html
Names
{{#names}}
{{name}}
{{/names}}
```
In mustache.js an object of partials may be passed as the third argument to `Mustache.render`. The object should be keyed by the name of the partial, and its value should be the partial text.
```js
Mustache.render(template, view, {
user: userTemplate
});
```
### Custom Delimiters
Custom delimiters can be used in place of `{{` and `}}` by setting the new values in JavaScript or in templates.
#### Setting in JavaScript
The `Mustache.tags` property holds an array consisting of the opening and closing tag values. Set custom values by passing a new array of tags to `render()`, which gets honored over the default values, or by overriding the `Mustache.tags` property itself:
```js
var customTags = [ '<%', '%>' ];
```
##### Pass Value into Render Method
```js
Mustache.render(template, view, {}, customTags);
```
##### Override Tags Property
```js
Mustache.tags = customTags;
// Subsequent parse() and render() calls will use customTags
```
#### Setting in Templates
Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings.
Consider the following contrived example:
```html+erb
* {{ default_tags }}
{{=<% %>=}}
* <% erb_style_tags %>
<%={{ }}=%>
* {{ default_tags_again }}
```
Here we have a list with three items. The first item uses the default tag style, the second uses ERB style as defined by the Set Delimiter tag, and the third returns to the default style after yet another Set Delimiter declaration.
According to [ctemplates](https://htmlpreview.github.io/?https://raw.githubusercontent.com/OlafvdSpek/ctemplate/master/doc/howto.html), this "is useful for languages like TeX, where double-braces may occur in the text and are awkward to use for markup."
Custom delimiters may not contain whitespace or the equals sign.
## Pre-parsing and Caching Templates
By default, when mustache.js first parses a template it keeps the full parsed token tree in a cache. The next time it sees that same template it skips the parsing step and renders the template much more quickly. If you'd like, you can do this ahead of time using `mustache.parse`.
```js
Mustache.parse(template);
// Then, sometime later.
Mustache.render(template, view);
```
## Plugins for JavaScript Libraries
mustache.js may be built specifically for several different client libraries, including the following:
- [jQuery](http://jquery.com/)
- [MooTools](http://mootools.net/)
- [Dojo](http://www.dojotoolkit.org/)
- [YUI](http://developer.yahoo.com/yui/)
- [qooxdoo](http://qooxdoo.org/)
These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands:
```bash
$ rake jquery
$ rake mootools
$ rake dojo
$ rake yui3
$ rake qooxdoo
```
## Testing
In order to run the tests you'll need to install [node](http://nodejs.org/).
You also need to install the sub module containing [Mustache specifications](http://github.com/mustache/spec) in the project root.
```bash
$ git submodule init
$ git submodule update
```
Install dependencies.
```bash
$ npm install
```
Then run the tests.
```bash
$ npm test
```
The test suite consists of both unit and integration tests. If a template isn't rendering correctly for you, you can make a test for it by doing the following:
1. Create a template file named `mytest.mustache` in the `test/_files`
directory. Replace `mytest` with the name of your test.
2. Create a corresponding view file named `mytest.js` in the same directory.
This file should contain a JavaScript object literal enclosed in
parentheses. See any of the other view files for an example.
3. Create a file with the expected output in `mytest.txt` in the same
directory.
Then, you can run the test with:
```bash
$ TEST=mytest npm run test-render
```
### Browser tests
Browser tests are not included in `npm test` as they run for too long, although they are ran automatically on Travis when merged into master. Run browser tests locally in any browser:
```bash
$ npm run test-browser-local
```
then point your browser to `http://localhost:8080/__zuul`
### Troubleshooting
#### npm install fails
Ensure to have a recent version of npm installed. While developing this project requires npm with support for `^` version ranges.
```bash
$ npm install -g npm
```
## Thanks
mustache.js wouldn't kick ass if it weren't for these fine souls:
* Chris Wanstrath / defunkt
* Alexander Lang / langalex
* Sebastian Cohnen / tisba
* J Chris Anderson / jchris
* Tom Robinson / tlrobinson
* Aaron Quint / quirkey
* Douglas Crockford
* Nikita Vasilyev / NV
* Elise Wood / glytch
* Damien Mathieu / dmathieu
* Jakub Kuźma / qoobaa
* Will Leinweber / will
* dpree
* Jason Smith / jhs
* Aaron Gibralter / agibralter
* Ross Boucher / boucher
* Matt Sanford / mzsanford
* Ben Cherry / bcherry
* Michael Jackson / mjackson
* Phillip Johnsen / phillipj
* David da Silva Contín / dasilvacontin
mustache.js-3.0.1/Rakefile 0000664 0000000 0000000 00000002766 13372117050 0015416 0 ustar 00root root 0000000 0000000 require 'rake'
require 'rake/clean'
task :default => :test
def minified_file
ENV['FILE'] || 'mustache.min.js'
end
desc "Run all tests"
task :test do
sh "./node_modules/.bin/mocha test"
end
desc "Make a compressed build in #{minified_file}"
task :minify do
sh "./node_modules/.bin/uglifyjs mustache.js > #{minified_file}"
end
desc "Run JSHint"
task :hint do
sh "./node_modules/.bin/jshint mustache.js"
end
# Creates a task that uses the various template wrappers to make a wrapped
# output file. There is some extra complexity because Dojo and YUI use
# different final locations.
def templated_build(name, final_location=nil)
short = name.downcase
source = File.join("wrappers", short)
dependencies = ["mustache.js"] + Dir.glob("#{source}/*.tpl.*")
target_js = final_location.nil? ? "#{short}.mustache.js" : "mustache.js"
desc "Package for #{name}"
task short.to_sym => dependencies do
puts "Packaging for #{name}"
mkdir_p final_location unless final_location.nil?
sources = [ "#{source}/mustache.js.pre", 'mustache.js', "#{source}/mustache.js.post" ]
relative_name = "#{final_location || '.'}/#{target_js}"
open(relative_name, 'w') do |f|
sources.each {|source| f << File.read(source) }
end
puts "Done, see #{relative_name}"
end
CLEAN.include(final_location.nil? ? target_js : final_location)
end
templated_build "jQuery"
templated_build "MooTools"
templated_build "Dojo", "dojox/string"
templated_build "YUI3", "yui3/mustache"
templated_build "qooxdoo"
mustache.js-3.0.1/bin/ 0000775 0000000 0000000 00000000000 13372117050 0014506 5 ustar 00root root 0000000 0000000 mustache.js-3.0.1/bin/mustache 0000775 0000000 0000000 00000006153 13372117050 0016252 0 ustar 00root root 0000000 0000000 #!/usr/bin/env node
var fs = require('fs'),
path = require('path');
var Mustache = require('..');
var pkg = require('../package');
var partials = {};
var partialsPaths = [];
var partialArgIndex = -1;
while ((partialArgIndex = process.argv.indexOf('-p')) > -1) {
partialsPaths.push(process.argv.splice(partialArgIndex, 2)[1]);
}
var viewArg = process.argv[2];
var templateArg = process.argv[3];
var outputArg = process.argv[4];
if (hasVersionArg()) {
return console.log(pkg.version);
}
if (!templateArg || !viewArg) {
console.error('Syntax: mustache [output]');
process.exit(1);
}
run(readPartials, readView, readTemplate, render, toStdout);
/**
* Runs a list of functions as a waterfall.
* Functions are runned one after the other in order, providing each
* function the returned values of all the previously invoked functions.
* Each function is expected to exit the process if an error occurs.
*/
function run (/*args*/) {
var values = [];
var fns = Array.prototype.slice.call(arguments);
function invokeNextFn (val) {
values.unshift(val);
if (fns.length === 0) return;
invoke(fns.shift());
}
function invoke (fn) {
fn.apply(null, [invokeNextFn].concat(values));
}
invoke(fns.shift());
}
function readView (cb) {
var view = isStdin(viewArg) ? process.openStdin() : fs.createReadStream(viewArg);
streamToStr(view, function onDone (str) {
cb(parseView(str));
});
}
function parseView (str) {
try {
return JSON.parse(str);
} catch (ex) {
console.error(
'Shooot, could not parse view as JSON.\n' +
'Tips: functions are not valid JSON and keys / values must be surround with double quotes.\n\n' +
ex.stack);
process.exit(1);
}
}
function readPartials (cb) {
if (!partialsPaths.length) return cb();
var partialPath = partialsPaths.pop();
var partial = fs.createReadStream(partialPath);
streamToStr(partial, function onDone (str) {
partials[getPartialName(partialPath)] = str;
readPartials(cb);
});
}
function readTemplate (cb) {
var template = fs.createReadStream(templateArg);
streamToStr(template, cb);
}
function render (cb, templateStr, jsonView) {
cb(Mustache.render(templateStr, jsonView, partials));
}
function toStdout (cb, str) {
if (outputArg) {
cb(fs.writeFileSync(outputArg, str));
} else {
cb(process.stdout.write(str));
}
}
function streamToStr (stream, cb) {
var data = '';
stream.on('data', function onData (chunk) {
data += chunk;
}).once('end', function onEnd () {
cb(data.toString());
}).on('error', function onError (err) {
if (wasNotFound(err)) {
console.error('Could not find file:', err.path);
} else {
console.error('Error while reading file:', err.message);
}
process.exit(1);
});
}
function isStdin (view) {
return view === '-';
}
function wasNotFound (err) {
return err.code && err.code === 'ENOENT';
}
function hasVersionArg () {
return ['--version', '-v'].some(function matchInArgs (opt) {
return process.argv.indexOf(opt) > -1;
});
}
function getPartialName (filename) {
return path.basename(filename, '.mustache');
}
mustache.js-3.0.1/bower.json 0000664 0000000 0000000 00000000672 13372117050 0015754 0 ustar 00root root 0000000 0000000 {
"name": "mustache.js",
"main": "mustache.js",
"homepage": "https://github.com/janl/mustache.js",
"authors": [
"mustache.js Authors "
],
"description": "Logic-less {{mustache}} templates with JavaScript",
"keywords": ["mustache", "template", "templates", "ejs"],
"moduleType": [
"amd",
"globals",
"node"
],
"license": "MIT",
"ignore": [
"**/.*",
"test"
]
}
mustache.js-3.0.1/hooks/ 0000775 0000000 0000000 00000000000 13372117050 0015061 5 ustar 00root root 0000000 0000000 mustache.js-3.0.1/hooks/install-hooks.sh 0000775 0000000 0000000 00000001613 13372117050 0020210 0 ustar 00root root 0000000 0000000 #!/bin/bash
HOOK_NAMES="pre-commit"
HOOK_DIR=$(git rev-parse --show-toplevel)/.git/hooks
INSTALL_DIR=$(git rev-parse --show-toplevel)/hooks
COLOR_GREEN=`tput setaf 2`
COLOR_RESET=`tput sgr0`
for hook in $HOOK_NAMES; do
echo -n "Installing $hook hook..."
# If the hook already exists, is executable, and is not a symlink
if [ ! -h $HOOK_DIR/$hook -a -x $HOOK_DIR/$hook ]; then
echo -n " Hook already exists, saving old hook backup at $HOOK_DIR/$hook.local..."
mv $HOOK_DIR/$hook $HOOK_DIR/$hook.local
fi
# create the symlink, overwriting the file if it exists
# probably the only way this would happen is if you're using an old version of git
# -- back when the sample hooks were not executable, instead of being named ____.sample
echo -n " Creating symlink..."
ln -s -f $INSTALL_DIR/$hook $HOOK_DIR
echo "${COLOR_GREEN} Done! ✓${COLOR_RESET}"
done mustache.js-3.0.1/hooks/pre-commit 0000775 0000000 0000000 00000003445 13372117050 0017071 0 ustar 00root root 0000000 0000000 #!/usr/bin/env ruby
require 'json'
def puts_c(color, str)
puts "\x1b[#{color}m#{str}\x1b[0m"
end
class Source
attr_accessor :path, :v_regex
def initialize(path, v_regex)
@path = path
@v_regex = v_regex
end
end
class Bumper
attr_accessor :sources, :bumped, :target_v
def initialize(sources)
@sources = sources
end
def start
# get package.json version
package = JSON.parse File.read 'package.json'
@target_v = package['version']
@bumped = false
@sources.each {|source| bump_source(source)}
# if bumped, do extra stuff and notify the user
if @bumped
# minify `mustache.js` using the Rakefile task
puts "> minifying `mustache.js`..."
`rake minify`
# stage files for commit
`git add package.json`
@sources.each {|source| `git add #{source.path}`}
`git add mustache.min.js`
`git commit -m ":ship: bump to version #{@target_v}"`
# notify codemonkey
puts "staged bumped files and created commit"
puts_c 32, "successfully bumped version to #{@target_v}!"
puts_c 33, "don't forget to `npm publish` and `spm publish`!"
end
exit 0
end
def bump_source(source)
file_buffer = File.read source.path
if match = file_buffer.match(source.v_regex)
file_v = match.captures[0]
if @target_v != file_v
did_bump
puts "> bumping version in file '#{source.path}': #{file_v} -> #{@target_v}..."
file_buffer[source.v_regex, 1] = @target_v
File.open(source.path, 'w') { |f| f.write file_buffer }
end
else
puts_c 31, "ERROR: Can't find version in '#{source.path}'"
exit 1
end
end
def did_bump
if !@bumped
puts 'bump detected!'
end
@bumped = true
end
end
bumper = Bumper.new([
Source.new('mustache.js', /mustache.version = '([\d\.]*)'/),
Source.new('mustache.js.nuspec', /([\d\.]*)<\/version>/),
])
bumper.start
mustache.js-3.0.1/mustache.js 0000664 0000000 0000000 00000052464 13372117050 0016120 0 ustar 00root root 0000000 0000000 /*!
* mustache.js - Logic-less {{mustache}} templates with JavaScript
* http://github.com/janl/mustache.js
*/
/*global define: false Mustache: true*/
(function defineMustache (global, factory) {
if (typeof exports === 'object' && exports && typeof exports.nodeName !== 'string') {
factory(exports); // CommonJS
} else if (typeof define === 'function' && define.amd) {
define(['exports'], factory); // AMD
} else {
global.Mustache = {};
factory(global.Mustache); // script, wsh, asp
}
}(this, function mustacheFactory (mustache) {
var objectToString = Object.prototype.toString;
var isArray = Array.isArray || function isArrayPolyfill (object) {
return objectToString.call(object) === '[object Array]';
};
function isFunction (object) {
return typeof object === 'function';
}
/**
* More correct typeof string handling array
* which normally returns typeof 'object'
*/
function typeStr (obj) {
return isArray(obj) ? 'array' : typeof obj;
}
function escapeRegExp (string) {
return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
}
/**
* Null safe way of checking whether or not an object,
* including its prototype, has a given property
*/
function hasProperty (obj, propName) {
return obj != null && typeof obj === 'object' && (propName in obj);
}
/**
* Safe way of detecting whether or not the given thing is a primitive and
* whether it has the given property
*/
function primitiveHasOwnProperty (primitive, propName) {
return (
primitive != null
&& typeof primitive !== 'object'
&& primitive.hasOwnProperty
&& primitive.hasOwnProperty(propName)
);
}
// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
// See https://github.com/janl/mustache.js/issues/189
var regExpTest = RegExp.prototype.test;
function testRegExp (re, string) {
return regExpTest.call(re, string);
}
var nonSpaceRe = /\S/;
function isWhitespace (string) {
return !testRegExp(nonSpaceRe, string);
}
var entityMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escapeHtml (string) {
return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
return entityMap[s];
});
}
var whiteRe = /\s*/;
var spaceRe = /\s+/;
var equalsRe = /\s*=/;
var curlyRe = /\s*\}/;
var tagRe = /#|\^|\/|>|\{|&|=|!/;
/**
* Breaks up the given `template` string into a tree of tokens. If the `tags`
* argument is given here it must be an array with two string values: the
* opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
* course, the default is to use mustaches (i.e. mustache.tags).
*
* A token is an array with at least 4 elements. The first element is the
* mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
* did not contain a symbol (i.e. {{myValue}}) this element is "name". For
* all text that appears outside a symbol this element is "text".
*
* The second element of a token is its "value". For mustache tags this is
* whatever else was inside the tag besides the opening symbol. For text tokens
* this is the text itself.
*
* The third and fourth elements of the token are the start and end indices,
* respectively, of the token in the original template.
*
* Tokens that are the root node of a subtree contain two more elements: 1) an
* array of tokens in the subtree and 2) the index in the original template at
* which the closing tag for that section begins.
*/
function parseTemplate (template, tags) {
if (!template)
return [];
var sections = []; // Stack to hold section tokens
var tokens = []; // Buffer to hold the tokens
var spaces = []; // Indices of whitespace tokens on the current line
var hasTag = false; // Is there a {{tag}} on the current line?
var nonSpace = false; // Is there a non-space char on the current line?
// Strips all whitespace tokens array for the current line
// if there was a {{#tag}} on it and otherwise only space.
function stripSpace () {
if (hasTag && !nonSpace) {
while (spaces.length)
delete tokens[spaces.pop()];
} else {
spaces = [];
}
hasTag = false;
nonSpace = false;
}
var openingTagRe, closingTagRe, closingCurlyRe;
function compileTags (tagsToCompile) {
if (typeof tagsToCompile === 'string')
tagsToCompile = tagsToCompile.split(spaceRe, 2);
if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
throw new Error('Invalid tags: ' + tagsToCompile);
openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
}
compileTags(tags || mustache.tags);
var scanner = new Scanner(template);
var start, type, value, chr, token, openSection;
while (!scanner.eos()) {
start = scanner.pos;
// Match any text between tags.
value = scanner.scanUntil(openingTagRe);
if (value) {
for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
chr = value.charAt(i);
if (isWhitespace(chr)) {
spaces.push(tokens.length);
} else {
nonSpace = true;
}
tokens.push([ 'text', chr, start, start + 1 ]);
start += 1;
// Check for whitespace on the current line.
if (chr === '\n')
stripSpace();
}
}
// Match the opening tag.
if (!scanner.scan(openingTagRe))
break;
hasTag = true;
// Get the tag type.
type = scanner.scan(tagRe) || 'name';
scanner.scan(whiteRe);
// Get the tag value.
if (type === '=') {
value = scanner.scanUntil(equalsRe);
scanner.scan(equalsRe);
scanner.scanUntil(closingTagRe);
} else if (type === '{') {
value = scanner.scanUntil(closingCurlyRe);
scanner.scan(curlyRe);
scanner.scanUntil(closingTagRe);
type = '&';
} else {
value = scanner.scanUntil(closingTagRe);
}
// Match the closing tag.
if (!scanner.scan(closingTagRe))
throw new Error('Unclosed tag at ' + scanner.pos);
token = [ type, value, start, scanner.pos ];
tokens.push(token);
if (type === '#' || type === '^') {
sections.push(token);
} else if (type === '/') {
// Check section nesting.
openSection = sections.pop();
if (!openSection)
throw new Error('Unopened section "' + value + '" at ' + start);
if (openSection[1] !== value)
throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
} else if (type === 'name' || type === '{' || type === '&') {
nonSpace = true;
} else if (type === '=') {
// Set the tags for the next time around.
compileTags(value);
}
}
// Make sure there are no open sections when we're done.
openSection = sections.pop();
if (openSection)
throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
return nestTokens(squashTokens(tokens));
}
/**
* Combines the values of consecutive text tokens in the given `tokens` array
* to a single token.
*/
function squashTokens (tokens) {
var squashedTokens = [];
var token, lastToken;
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
token = tokens[i];
if (token) {
if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
lastToken[1] += token[1];
lastToken[3] = token[3];
} else {
squashedTokens.push(token);
lastToken = token;
}
}
}
return squashedTokens;
}
/**
* Forms the given array of `tokens` into a nested tree structure where
* tokens that represent a section have two additional items: 1) an array of
* all tokens that appear in that section and 2) the index in the original
* template that represents the end of that section.
*/
function nestTokens (tokens) {
var nestedTokens = [];
var collector = nestedTokens;
var sections = [];
var token, section;
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
token = tokens[i];
switch (token[0]) {
case '#':
case '^':
collector.push(token);
sections.push(token);
collector = token[4] = [];
break;
case '/':
section = sections.pop();
section[5] = token[2];
collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
break;
default:
collector.push(token);
}
}
return nestedTokens;
}
/**
* A simple string scanner that is used by the template parser to find
* tokens in template strings.
*/
function Scanner (string) {
this.string = string;
this.tail = string;
this.pos = 0;
}
/**
* Returns `true` if the tail is empty (end of string).
*/
Scanner.prototype.eos = function eos () {
return this.tail === '';
};
/**
* Tries to match the given regular expression at the current position.
* Returns the matched text if it can match, the empty string otherwise.
*/
Scanner.prototype.scan = function scan (re) {
var match = this.tail.match(re);
if (!match || match.index !== 0)
return '';
var string = match[0];
this.tail = this.tail.substring(string.length);
this.pos += string.length;
return string;
};
/**
* Skips all text until the given regular expression can be matched. Returns
* the skipped string, which is the entire tail if no match can be made.
*/
Scanner.prototype.scanUntil = function scanUntil (re) {
var index = this.tail.search(re), match;
switch (index) {
case -1:
match = this.tail;
this.tail = '';
break;
case 0:
match = '';
break;
default:
match = this.tail.substring(0, index);
this.tail = this.tail.substring(index);
}
this.pos += match.length;
return match;
};
/**
* Represents a rendering context by wrapping a view object and
* maintaining a reference to the parent context.
*/
function Context (view, parentContext) {
this.view = view;
this.cache = { '.': this.view };
this.parent = parentContext;
}
/**
* Creates a new context using the given view with this context
* as the parent.
*/
Context.prototype.push = function push (view) {
return new Context(view, this);
};
/**
* Returns the value of the given name in this context, traversing
* up the context hierarchy if the value is absent in this context's view.
*/
Context.prototype.lookup = function lookup (name) {
var cache = this.cache;
var value;
if (cache.hasOwnProperty(name)) {
value = cache[name];
} else {
var context = this, intermediateValue, names, index, lookupHit = false;
while (context) {
if (name.indexOf('.') > 0) {
intermediateValue = context.view;
names = name.split('.');
index = 0;
/**
* Using the dot notion path in `name`, we descend through the
* nested objects.
*
* To be certain that the lookup has been successful, we have to
* check if the last object in the path actually has the property
* we are looking for. We store the result in `lookupHit`.
*
* This is specially necessary for when the value has been set to
* `undefined` and we want to avoid looking up parent contexts.
*
* In the case where dot notation is used, we consider the lookup
* to be successful even if the last "object" in the path is
* not actually an object but a primitive (e.g., a string, or an
* integer), because it is sometimes useful to access a property
* of an autoboxed primitive, such as the length of a string.
**/
while (intermediateValue != null && index < names.length) {
if (index === names.length - 1)
lookupHit = (
hasProperty(intermediateValue, names[index])
|| primitiveHasOwnProperty(intermediateValue, names[index])
);
intermediateValue = intermediateValue[names[index++]];
}
} else {
intermediateValue = context.view[name];
/**
* Only checking against `hasProperty`, which always returns `false` if
* `context.view` is not an object. Deliberately omitting the check
* against `primitiveHasOwnProperty` if dot notation is not used.
*
* Consider this example:
* ```
* Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"})
* ```
*
* If we were to check also against `primitiveHasOwnProperty`, as we do
* in the dot notation case, then render call would return:
*
* "The length of a football field is 9."
*
* rather than the expected:
*
* "The length of a football field is 100 yards."
**/
lookupHit = hasProperty(context.view, name);
}
if (lookupHit) {
value = intermediateValue;
break;
}
context = context.parent;
}
cache[name] = value;
}
if (isFunction(value))
value = value.call(this.view);
return value;
};
/**
* A Writer knows how to take a stream of tokens and render them to a
* string, given a context. It also maintains a cache of templates to
* avoid the need to parse the same template twice.
*/
function Writer () {
this.cache = {};
}
/**
* Clears all cached templates in this writer.
*/
Writer.prototype.clearCache = function clearCache () {
this.cache = {};
};
/**
* Parses and caches the given `template` according to the given `tags` or
* `mustache.tags` if `tags` is omitted, and returns the array of tokens
* that is generated from the parse.
*/
Writer.prototype.parse = function parse (template, tags) {
var cache = this.cache;
var cacheKey = template + ':' + (tags || mustache.tags).join(':');
var tokens = cache[cacheKey];
if (tokens == null)
tokens = cache[cacheKey] = parseTemplate(template, tags);
return tokens;
};
/**
* High-level method that is used to render the given `template` with
* the given `view`.
*
* The optional `partials` argument may be an object that contains the
* names and templates of partials that are used in the template. It may
* also be a function that is used to load partial templates on the fly
* that takes a single argument: the name of the partial.
*
* If the optional `tags` argument is given here it must be an array with two
* string values: the opening and closing tags used in the template (e.g.
* [ "<%", "%>" ]). The default is to mustache.tags.
*/
Writer.prototype.render = function render (template, view, partials, tags) {
var tokens = this.parse(template, tags);
var context = (view instanceof Context) ? view : new Context(view);
return this.renderTokens(tokens, context, partials, template, tags);
};
/**
* Low-level method that renders the given array of `tokens` using
* the given `context` and `partials`.
*
* Note: The `originalTemplate` is only ever used to extract the portion
* of the original template that was contained in a higher-order section.
* If the template doesn't use higher-order sections, this argument may
* be omitted.
*/
Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, tags) {
var buffer = '';
var token, symbol, value;
for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
value = undefined;
token = tokens[i];
symbol = token[0];
if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
else if (symbol === '>') value = this.renderPartial(token, context, partials, tags);
else if (symbol === '&') value = this.unescapedValue(token, context);
else if (symbol === 'name') value = this.escapedValue(token, context);
else if (symbol === 'text') value = this.rawValue(token);
if (value !== undefined)
buffer += value;
}
return buffer;
};
Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate) {
var self = this;
var buffer = '';
var value = context.lookup(token[1]);
// This function is used to render an arbitrary template
// in the current context by higher-order sections.
function subRender (template) {
return self.render(template, context, partials);
}
if (!value) return;
if (isArray(value)) {
for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
}
} else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
} else if (isFunction(value)) {
if (typeof originalTemplate !== 'string')
throw new Error('Cannot use higher-order sections without the original template');
// Extract the portion of the original template that the section contains.
value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
if (value != null)
buffer += value;
} else {
buffer += this.renderTokens(token[4], context, partials, originalTemplate);
}
return buffer;
};
Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate) {
var value = context.lookup(token[1]);
// Use JavaScript's definition of falsy. Include empty arrays.
// See https://github.com/janl/mustache.js/issues/186
if (!value || (isArray(value) && value.length === 0))
return this.renderTokens(token[4], context, partials, originalTemplate);
};
Writer.prototype.renderPartial = function renderPartial (token, context, partials, tags) {
if (!partials) return;
var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
if (value != null)
return this.renderTokens(this.parse(value, tags), context, partials, value);
};
Writer.prototype.unescapedValue = function unescapedValue (token, context) {
var value = context.lookup(token[1]);
if (value != null)
return value;
};
Writer.prototype.escapedValue = function escapedValue (token, context) {
var value = context.lookup(token[1]);
if (value != null)
return mustache.escape(value);
};
Writer.prototype.rawValue = function rawValue (token) {
return token[1];
};
mustache.name = 'mustache.js';
mustache.version = '3.0.1';
mustache.tags = [ '{{', '}}' ];
// All high-level mustache.* functions use this writer.
var defaultWriter = new Writer();
/**
* Clears all cached templates in the default writer.
*/
mustache.clearCache = function clearCache () {
return defaultWriter.clearCache();
};
/**
* Parses and caches the given template in the default writer and returns the
* array of tokens it contains. Doing this ahead of time avoids the need to
* parse templates on the fly as they are rendered.
*/
mustache.parse = function parse (template, tags) {
return defaultWriter.parse(template, tags);
};
/**
* Renders the `template` with the given `view` and `partials` using the
* default writer. If the optional `tags` argument is given here it must be an
* array with two string values: the opening and closing tags used in the
* template (e.g. [ "<%", "%>" ]). The default is to mustache.tags.
*/
mustache.render = function render (template, view, partials, tags) {
if (typeof template !== 'string') {
throw new TypeError('Invalid template! Template should be a "string" ' +
'but "' + typeStr(template) + '" was given as the first ' +
'argument for mustache#render(template, view, partials)');
}
return defaultWriter.render(template, view, partials, tags);
};
// This is here for backwards compatibility with 0.4.x.,
/*eslint-disable */ // eslint wants camel cased function name
mustache.to_html = function to_html (template, view, partials, send) {
/*eslint-enable*/
var result = mustache.render(template, view, partials);
if (isFunction(send)) {
send(result);
} else {
return result;
}
};
// Export the escaping function so that the user may override it.
// See https://github.com/janl/mustache.js/issues/244
mustache.escape = escapeHtml;
// Export these mainly for testing, but also for advanced usage.
mustache.Scanner = Scanner;
mustache.Context = Context;
mustache.Writer = Writer;
return mustache;
}));
mustache.js-3.0.1/mustache.js.nuspec 0000664 0000000 0000000 00000001036 13372117050 0017401 0 ustar 00root root 0000000 0000000
mustache.js
3.0.1
mustache.js Authors
https://github.com/janl/mustache.js/blob/master/LICENSE
http://mustache.github.com/
false
Logic-less templates in JavaScript.
mustache template templates javascript