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 12KB

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