You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 13KB

14 years ago
16 years ago
13 years ago
13 years ago
13 years ago
13 years ago
14 years ago
16 years ago
13 years ago
14 years ago
13 years ago
14 years ago
13 years ago
11 years ago
11 years ago
16 years ago
14 years ago
16 years ago
13 years ago
14 years ago
14 years ago
13 years ago
13 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
13 years ago
13 years ago
13 years ago
13 years ago
16 years ago
13 years ago
16 years ago
16 years ago
13 years ago
16 years ago
16 years ago
16 years ago
13 years ago
16 years ago
13 years ago
16 years ago
16 years ago
14 years ago
13 years ago
14 years ago
14 years ago
13 years ago
14 years ago
14 years ago
14 years ago
14 years ago
13 years ago
12 years ago
14 years ago
14 years ago
14 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. # mustache.js - Logic-less {{mustache}} templates with JavaScript
  2. > What could be more logical awesome than no logic at all?
  3. [mustache.js](http://github.com/janl/mustache.js) is an implementation of the [mustache](http://mustache.github.com/) template system in JavaScript.
  4. [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.
  5. 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.
  6. For a language-agnostic overview of mustache's template syntax, see the `mustache(5)` [manpage](http://mustache.github.com/mustache.5.html).
  7. ## Where to use mustache.js?
  8. 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.
  9. 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.
  10. And this will be your templates after you use Mustache:
  11. !['stache](http://d24w6bsrhbeh9d.cloudfront.net/photo/aZPNGon_460sa.gif)
  12. ## Who uses mustache.js?
  13. 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!
  14. ## Contributing
  15. 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.
  16. ### Your First Contribution
  17. - review a [Pull Request](https://github.com/janl/mustache.js/pulls)
  18. - fix an [Issue](https://github.com/janl/mustache.js/issues)
  19. - update the [documentation](https://github.com/janl/mustache.js#usage)
  20. - make a website
  21. - write a tutorial
  22. * * *
  23. ## Usage
  24. Below is quick example how to use mustache.js:
  25. ```js
  26. var view = {
  27. title: "Joe",
  28. calc: function () {
  29. return 2 + 4;
  30. }
  31. };
  32. var output = Mustache.render("{{title}} spends {{calc}}", view);
  33. ```
  34. 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.
  35. ## Templates
  36. 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.
  37. There are several techniques that can be used to load templates and hand them to mustache.js, here are two of them:
  38. #### Include Templates
  39. 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`:
  40. ```html
  41. <html>
  42. <body onload="loadUser">
  43. <div id="target">Loading...</div>
  44. <script id="template" type="x-tmpl-mustache">
  45. Hello {{ name }}!
  46. </script>
  47. </body>
  48. </html>
  49. ```
  50. ```js
  51. function loadUser() {
  52. var template = $('#template').html();
  53. Mustache.parse(template); // optional, speeds up future uses
  54. var rendered = Mustache.render(template, {name: "Luke"});
  55. $('#target').html(rendered);
  56. }
  57. ```
  58. #### Load External Templates
  59. If your templates reside in individual files, you can load them asynchronously and render them when they arrive. Another example using `jQuery`:
  60. ```js
  61. function loadUser() {
  62. $.get('template.mst', function(template) {
  63. var rendered = Mustache.render(template, {name: "Luke"});
  64. $('#target').html(rendered);
  65. });
  66. }
  67. ```
  68. ### Variables
  69. 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.
  70. 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.
  71. View:
  72. ```json
  73. {
  74. "name": "Chris",
  75. "company": "<b>GitHub</b>"
  76. }
  77. ```
  78. Template:
  79. ```html
  80. * {{name}}
  81. * {{age}}
  82. * {{company}}
  83. * {{{company}}}
  84. * {{&company}}
  85. ```
  86. Output:
  87. ```html
  88. * Chris
  89. *
  90. * &lt;b&gt;GitHub&lt;/b&gt;
  91. * <b>GitHub</b>
  92. * <b>GitHub</b>
  93. ```
  94. JavaScript's dot notation may be used to access keys that are properties of objects in a view.
  95. View:
  96. ```json
  97. {
  98. "name": {
  99. "first": "Michael",
  100. "last": "Jackson"
  101. },
  102. "age": "RIP"
  103. }
  104. ```
  105. Template:
  106. ```html
  107. * {{name.first}} {{name.last}}
  108. * {{age}}
  109. ```
  110. Output:
  111. ```html
  112. * Michael Jackson
  113. * RIP
  114. ```
  115. ### Sections
  116. Sections render blocks of text one or more times, depending on the value of the key in the current context.
  117. 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".
  118. The behavior of the section is determined by the value of the key.
  119. #### False Values or Empty Lists
  120. 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.
  121. View:
  122. ```json
  123. {
  124. "person": false
  125. }
  126. ```
  127. Template:
  128. ```html
  129. Shown.
  130. {{#person}}
  131. Never shown!
  132. {{/person}}
  133. ```
  134. Output:
  135. ```html
  136. Shown.
  137. ```
  138. #### Non-Empty Lists
  139. 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.
  140. 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.
  141. View:
  142. ```json
  143. {
  144. "stooges": [
  145. { "name": "Moe" },
  146. { "name": "Larry" },
  147. { "name": "Curly" }
  148. ]
  149. }
  150. ```
  151. Template:
  152. ```html
  153. {{#stooges}}
  154. <b>{{name}}</b>
  155. {{/stooges}}
  156. ```
  157. Output:
  158. ```html
  159. <b>Moe</b>
  160. <b>Larry</b>
  161. <b>Curly</b>
  162. ```
  163. When looping over an array of strings, a `.` can be used to refer to the current item in the list.
  164. View:
  165. ```json
  166. {
  167. "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
  168. }
  169. ```
  170. Template:
  171. ```html
  172. {{#musketeers}}
  173. * {{.}}
  174. {{/musketeers}}
  175. ```
  176. Output:
  177. ```html
  178. * Athos
  179. * Aramis
  180. * Porthos
  181. * D'Artagnan
  182. ```
  183. 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.
  184. View:
  185. ```js
  186. {
  187. "beatles": [
  188. { "firstName": "John", "lastName": "Lennon" },
  189. { "firstName": "Paul", "lastName": "McCartney" },
  190. { "firstName": "George", "lastName": "Harrison" },
  191. { "firstName": "Ringo", "lastName": "Starr" }
  192. ],
  193. "name": function () {
  194. return this.firstName + " " + this.lastName;
  195. }
  196. }
  197. ```
  198. Template:
  199. ```html
  200. {{#beatles}}
  201. * {{name}}
  202. {{/beatles}}
  203. ```
  204. Output:
  205. ```html
  206. * John Lennon
  207. * Paul McCartney
  208. * George Harrison
  209. * Ringo Starr
  210. ```
  211. #### Functions
  212. 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.
  213. View:
  214. ```js
  215. {
  216. "name": "Tater",
  217. "bold": function () {
  218. return function (text, render) {
  219. return "<b>" + render(text) + "</b>";
  220. }
  221. }
  222. }
  223. ```
  224. Template:
  225. ```html
  226. {{#bold}}Hi {{name}}.{{/bold}}
  227. ```
  228. Output:
  229. ```html
  230. <b>Hi Tater.</b>
  231. ```
  232. ### Inverted Sections
  233. 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`, or an empty list.
  234. View:
  235. ```json
  236. {
  237. "repos": []
  238. }
  239. ```
  240. Template:
  241. ```html
  242. {{#repos}}<b>{{name}}</b>{{/repos}}
  243. {{^repos}}No repos :({{/repos}}
  244. ```
  245. Output:
  246. ```html
  247. No repos :(
  248. ```
  249. ### Comments
  250. Comments begin with a bang and are ignored. The following template:
  251. ```html
  252. <h1>Today{{! ignore me }}.</h1>
  253. ```
  254. Will render as follows:
  255. ```html
  256. <h1>Today.</h1>
  257. ```
  258. Comments may contain newlines.
  259. ### Partials
  260. Partials begin with a greater than sign, like {{> box}}.
  261. Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops.
  262. They also inherit the calling context. Whereas in ERB you may have this:
  263. ```html+erb
  264. <%= partial :next_more, :start => start, :size => size %>
  265. ```
  266. Mustache requires only this:
  267. ```html
  268. {{> next_more}}
  269. ```
  270. 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, or template expansion, even though it's not literally true.
  271. For example, this template and partial:
  272. base.mustache:
  273. <h2>Names</h2>
  274. {{#names}}
  275. {{> user}}
  276. {{/names}}
  277. user.mustache:
  278. <strong>{{name}}</strong>
  279. Can be thought of as a single, expanded template:
  280. ```html
  281. <h2>Names</h2>
  282. {{#names}}
  283. <strong>{{name}}</strong>
  284. {{/names}}
  285. ```
  286. 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.
  287. ```js
  288. Mustache.render(template, view, {
  289. user: userTemplate
  290. });
  291. ```
  292. ### Set Delimiter
  293. Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings.
  294. Consider the following contrived example:
  295. ```
  296. * {{ default_tags }}
  297. {{=<% %>=}}
  298. * <% erb_style_tags %>
  299. <%={{ }}=%>
  300. * {{ default_tags_again }}
  301. ```
  302. 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.
  303. According to [ctemplates](http://google-ctemplate.googlecode.com/svn/trunk/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."
  304. Custom delimiters may not contain whitespace or the equals sign.
  305. ## Pre-parsing and Caching Templates
  306. 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`.
  307. ```js
  308. Mustache.parse(template);
  309. // Then, sometime later.
  310. Mustache.render(template, view);
  311. ```
  312. ## Plugins for JavaScript Libraries
  313. mustache.js may be built specifically for several different client libraries, including the following:
  314. - [jQuery](http://jquery.com/)
  315. - [MooTools](http://mootools.net/)
  316. - [Dojo](http://www.dojotoolkit.org/)
  317. - [YUI](http://developer.yahoo.com/yui/)
  318. - [qooxdoo](http://qooxdoo.org/)
  319. These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands:
  320. $ rake jquery
  321. $ rake mootools
  322. $ rake dojo
  323. $ rake yui3
  324. $ rake qooxdoo
  325. ## Testing
  326. The mustache.js test suite uses the [mocha](http://visionmedia.github.com/mocha/) testing framework. In order to run the tests you'll need to install [node](http://nodejs.org/). Once that's done you can install mocha using [npm](http://npmjs.org/).
  327. $ npm install -g mocha
  328. You also need to install the sub module containing [Mustache specifications](http://github.com/mustache/spec) in the project root.
  329. $ git submodule init
  330. $ git submodule update
  331. Then run the tests.
  332. $ mocha test
  333. 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:
  334. 1. Create a template file named `mytest.mustache` in the `test/_files`
  335. directory. Replace `mytest` with the name of your test.
  336. 2. Create a corresponding view file named `mytest.js` in the same directory.
  337. This file should contain a JavaScript object literal enclosed in
  338. parentheses. See any of the other view files for an example.
  339. 3. Create a file with the expected output in `mytest.txt` in the same
  340. directory.
  341. Then, you can run the test with:
  342. $ TEST=mytest mocha test/render-test.js
  343. ## Thanks
  344. mustache.js wouldn't kick ass if it weren't for these fine souls:
  345. * Chris Wanstrath / defunkt
  346. * Alexander Lang / langalex
  347. * Sebastian Cohnen / tisba
  348. * J Chris Anderson / jchris
  349. * Tom Robinson / tlrobinson
  350. * Aaron Quint / quirkey
  351. * Douglas Crockford
  352. * Nikita Vasilyev / NV
  353. * Elise Wood / glytch
  354. * Damien Mathieu / dmathieu
  355. * Jakub Kuźma / qoobaa
  356. * Will Leinweber / will
  357. * dpree
  358. * Jason Smith / jhs
  359. * Aaron Gibralter / agibralter
  360. * Ross Boucher / boucher
  361. * Matt Sanford / mzsanford
  362. * Ben Cherry / bcherry
  363. * Michael Jackson / mjijackson