Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

README.md 14KB

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