A Twitch.tv viewer reward and games system.
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.

400 lines
12 KiB

11 years ago
  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. var view = {
  15. title: "Joe",
  16. calc: function () {
  17. return 2 + 4;
  18. }
  19. };
  20. var output = Mustache.render("{{title}} spends {{calc}}", view);
  21. 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.
  22. ## Templates
  23. 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.
  24. There are several types of tags available in mustache.js.
  25. ### Variables
  26. 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.
  27. 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.
  28. View:
  29. {
  30. "name": "Chris",
  31. "company": "<b>GitHub</b>"
  32. }
  33. Template:
  34. * {{name}}
  35. * {{age}}
  36. * {{company}}
  37. * {{{company}}}
  38. * {{&company}}
  39. Output:
  40. * Chris
  41. *
  42. * &lt;b&gt;GitHub&lt;/b&gt;
  43. * <b>GitHub</b>
  44. * <b>GitHub</b>
  45. JavaScript's dot notation may be used to access keys that are properties of objects in a view.
  46. View:
  47. {
  48. "name": {
  49. "first": "Michael",
  50. "last": "Jackson"
  51. },
  52. "age": "RIP"
  53. }
  54. Template:
  55. * {{name.first}} {{name.last}}
  56. * {{age}}
  57. Output:
  58. * Michael Jackson
  59. * RIP
  60. ### Sections
  61. Sections render blocks of text one or more times, depending on the value of the key in the current context.
  62. 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".
  63. The behavior of the section is determined by the value of the key.
  64. #### False Values or Empty Lists
  65. If the `person` key does not exist, or exists and has a value of `null`, `undefined`, or `false`, or is an empty list, the block will not be rendered.
  66. View:
  67. {
  68. "person": false
  69. }
  70. Template:
  71. Shown.
  72. {{#person}}
  73. Never shown!
  74. {{/person}}
  75. Output:
  76. Shown.
  77. #### Non-Empty Lists
  78. 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.
  79. 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.
  80. View:
  81. {
  82. "stooges": [
  83. { "name": "Moe" },
  84. { "name": "Larry" },
  85. { "name": "Curly" }
  86. ]
  87. }
  88. Template:
  89. {{#stooges}}
  90. <b>{{name}}</b>
  91. {{/stooges}}
  92. Output:
  93. <b>Moe</b>
  94. <b>Larry</b>
  95. <b>Curly</b>
  96. When looping over an array of strings, a `.` can be used to refer to the current item in the list.
  97. View:
  98. {
  99. "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
  100. }
  101. Template:
  102. {{#musketeers}}
  103. * {{.}}
  104. {{/musketeers}}
  105. Output:
  106. * Athos
  107. * Aramis
  108. * Porthos
  109. * D'Artagnan
  110. 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.
  111. View:
  112. {
  113. "beatles": [
  114. { "firstName": "John", "lastName": "Lennon" },
  115. { "firstName": "Paul", "lastName": "McCartney" },
  116. { "firstName": "George", "lastName": "Harrison" },
  117. { "firstName": "Ringo", "lastName": "Starr" }
  118. ],
  119. "name": function () {
  120. return this.firstName + " " + this.lastName;
  121. }
  122. }
  123. Template:
  124. {{#beatles}}
  125. * {{name}}
  126. {{/beatles}}
  127. Output:
  128. * John Lennon
  129. * Paul McCartney
  130. * George Harrison
  131. * Ringo Starr
  132. #### Functions
  133. 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.
  134. View:
  135. {
  136. "name": "Tater",
  137. "bold": function () {
  138. return function (text, render) {
  139. return "<b>" + render(text) + "</b>";
  140. }
  141. }
  142. }
  143. Template:
  144. {{#bold}}Hi {{name}}.{{/bold}}
  145. Output:
  146. <b>Hi Tater.</b>
  147. ### Inverted Sections
  148. 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.
  149. View:
  150. {
  151. "repos": []
  152. }
  153. Template:
  154. {{#repos}}<b>{{name}}</b>{{/repos}}
  155. {{^repos}}No repos :({{/repos}}
  156. Output:
  157. No repos :(
  158. ### Comments
  159. Comments begin with a bang and are ignored. The following template:
  160. <h1>Today{{! ignore me }}.</h1>
  161. Will render as follows:
  162. <h1>Today.</h1>
  163. Comments may contain newlines.
  164. ### Partials
  165. Partials begin with a greater than sign, like {{> box}}.
  166. Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops.
  167. They also inherit the calling context. Whereas in ERB you may have this:
  168. <%= partial :next_more, :start => start, :size => size %>
  169. Mustache requires only this:
  170. {{> next_more}}
  171. 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.
  172. For example, this template and partial:
  173. base.mustache:
  174. <h2>Names</h2>
  175. {{#names}}
  176. {{> user}}
  177. {{/names}}
  178. user.mustache:
  179. <strong>{{name}}</strong>
  180. Can be thought of as a single, expanded template:
  181. <h2>Names</h2>
  182. {{#names}}
  183. <strong>{{name}}</strong>
  184. {{/names}}
  185. 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.
  186. ### Set Delimiter
  187. Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings.
  188. Consider the following contrived example:
  189. * {{ default_tags }}
  190. {{=<% %>=}}
  191. * <% erb_style_tags %>
  192. <%={{ }}=%>
  193. * {{ default_tags_again }}
  194. 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.
  195. 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."
  196. Custom delimiters may not contain whitespace or the equals sign.
  197. ### Compiled Templates
  198. Mustache templates can be compiled into JavaScript functions using `Mustache.compile` for improved rendering performance.
  199. If you have template views that are rendered multiple times, compiling your template into a JavaScript function will minimise the amount of work required for each re-render.
  200. Pre-compiled templates can also be generated server-side, for delivery to the browser as ready to use JavaScript functions, further reducing the amount of client side processing required for initialising templates.
  201. **Mustache.compile**
  202. Use `Mustache.compile` to compile standard Mustache string templates into reusable Mustache template functions.
  203. var compiledTemplate = Mustache.compile(stringTemplate);
  204. The function returned from `Mustache.compile` can then be called directly, passing in the template data as an argument (with an object of partials as an optional second parameter), to generate the final output.
  205. var templateOutput = compiledTemplate(templateData);
  206. **Mustache.compilePartial**
  207. Template partials can also be compiled using the `Mustache.compilePartial` function. The first parameter of this function, is the name of the partial as it appears within parent templates.
  208. Mustache.compilePartial('partial-name', stringTemplate);
  209. Compiled partials are then available to both `Mustache.render` and `Mustache.compile`.
  210. ## Plugins for JavaScript Libraries
  211. mustache.js may be built specifically for several different client libraries, including the following:
  212. - [jQuery](http://jquery.com/)
  213. - [MooTools](http://mootools.net/)
  214. - [Dojo](http://www.dojotoolkit.org/)
  215. - [YUI](http://developer.yahoo.com/yui/)
  216. - [qooxdoo](http://qooxdoo.org/)
  217. These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands:
  218. $ rake jquery
  219. $ rake mootools
  220. $ rake dojo
  221. $ rake yui
  222. $ rake qooxdoo
  223. ## Testing
  224. The mustache.js test suite uses the [vows](http://vowsjs.org/) testing framework. In order to run the tests you'll need to install [node](http://nodejs.org/). Once that's done you can install vows using [npm](http://npmjs.org/).
  225. $ npm install -g vows
  226. Then run the tests.
  227. $ vows --spec
  228. 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:
  229. 1. Create a template file named `mytest.mustache` in the `test/_files`
  230. directory. Replace `mytest` with the name of your test.
  231. 2. Create a corresponding view file named `mytest.js` in the same directory.
  232. This file should contain a JavaScript object literal enclosed in
  233. parentheses. See any of the other view files for an example.
  234. 3. Create a file with the expected output in `mytest.txt` in the same
  235. directory.
  236. Then, you can run the test with:
  237. $ TEST=mytest vows test/render_test.js
  238. ## Thanks
  239. mustache.js wouldn't kick ass if it weren't for these fine souls:
  240. * Chris Wanstrath / defunkt
  241. * Alexander Lang / langalex
  242. * Sebastian Cohnen / tisba
  243. * J Chris Anderson / jchris
  244. * Tom Robinson / tlrobinson
  245. * Aaron Quint / quirkey
  246. * Douglas Crockford
  247. * Nikita Vasilyev / NV
  248. * Elise Wood / glytch
  249. * Damien Mathieu / dmathieu
  250. * Jakub Kuźma / qoobaa
  251. * Will Leinweber / will
  252. * dpree
  253. * Jason Smith / jhs
  254. * Aaron Gibralter / agibralter
  255. * Ross Boucher / boucher
  256. * Matt Sanford / mzsanford
  257. * Ben Cherry / bcherry
  258. * Michael Jackson / mjijackson