Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

14 anos atrás
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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
  4. [Mustache](http://mustache.github.com/) template system in JavaScript.
  5. [Mustache](http://mustache.github.com/) is a logic-less template syntax. It can
  6. be used for HTML, config files, source code - anything. It works by expanding
  7. tags in a template using values provided in a hash or object.
  8. We call it "logic-less" because there are no if statements, else clauses, or for
  9. loops. Instead there are only tags. Some tags are replaced with a value, some
  10. nothing, and others a series of values.
  11. For a language-agnostic overview of Mustache's template syntax, see the
  12. `mustache(5)` [manpage](http://mustache.github.com/mustache.5.html).
  13. ## Where to use mustache.js?
  14. You can use mustache.js to render templates in many various scenarios where you
  15. can use JavaScript. For example, you can render templates in a browser,
  16. server-side using [node](http://nodejs.org/), in [CouchDB](http://couchdb.apache.org/)
  17. views, or in almost any other environment where you can use JavaScript.
  18. ## Who uses mustache.js?
  19. An updated list of mustache.js users is kept [on the Github wiki](http://wiki.github.com/janl/mustache.js/beard-competition).
  20. Add yourself or your company if you use mustache.js!
  21. ## Usage
  22. Below is quick example how to use mustache.js:
  23. var view = {
  24. title: "Joe",
  25. calc: function () {
  26. return 2 + 4;
  27. }
  28. };
  29. var output = Mustache.render("{{title}} spends {{calc}}", view);
  30. In this example, the `Mustache.render` function takes two parameters: 1) the
  31. [mustache](http://mustache.github.com/) template and 2) a `view` object that
  32. contains the data and code needed to render the template.
  33. ### CommonJS
  34. mustache.js is usable without any modification in both browsers and [CommonJS](http://www.commonjs.org/)
  35. environments like [node.js](http://nodejs.org/). To use it as a CommonJS module,
  36. simply require the file, like this:
  37. var Mustache = require("mustache");
  38. ## Templates
  39. A [mustache](http://mustache.github.com/) template is a string that contains
  40. any number of mustache tags. Tags are indicated by the double mustaches that
  41. surround them. `{{person}}` is a tag, as is `{{#person}}`. In both examples we
  42. refer to `person` as the tag's key.
  43. There are several types of tags available in mustache.js.
  44. ### Variables
  45. The most basic tag type is a simple variable. A `{{name}}` tag renders the value
  46. of the `name` key in the current context. If there is no such key, nothing is
  47. rendered.
  48. All variables are HTML-escaped by default. If you want to render unescaped HTML,
  49. use the triple mustache: `{{{name}}}`. You can also use `&` to unescape a
  50. variable.
  51. Template:
  52. * {{name}}
  53. * {{age}}
  54. * {{company}}
  55. * {{{company}}}
  56. * {{&company}}
  57. View:
  58. {
  59. "name": "Chris",
  60. "company": "<b>GitHub</b>"
  61. }
  62. Output:
  63. * Chris
  64. *
  65. * &lt;b&gt;GitHub&lt;/b&gt;
  66. * <b>GitHub</b>
  67. * <b>GitHub</b>
  68. JavaScript's dot notation may be used to access keys that are properties of
  69. objects in a view.
  70. Template:
  71. * {{name.first}} {{name.last}}
  72. * {{age}}
  73. View:
  74. {
  75. "name": {
  76. "first": "Michael",
  77. "last": "Jackson"
  78. },
  79. "age": "RIP"
  80. }
  81. Output:
  82. * Michael Jackson
  83. * RIP
  84. ### Sections
  85. Sections render blocks of text one or more times, depending on the value of the
  86. key in the current context.
  87. A section begins with a pound and ends with a slash. That is, `{{#person}}`
  88. begins a `person` section, while `{{/person}}` ends it. The text between the two
  89. tags is referred to as that section's "block".
  90. The behavior of the section is determined by the value of the key.
  91. #### False Values or Empty Lists
  92. If the `person` key exists and has a value of `null`, `undefined`, or `false`,
  93. or is an empty list, the block will not be rendered.
  94. Template:
  95. Shown.
  96. {{#nothin}}
  97. Never shown!
  98. {{/nothin}}
  99. View:
  100. {
  101. "person": true
  102. }
  103. Output:
  104. Shown.
  105. #### Non-Empty Lists
  106. If the `person` key exists and is not `null`, `undefined`, or `false`, and is
  107. not an empty list the block will be rendered one or more times.
  108. When the value is a list, the block is rendered once for each item in the list.
  109. The context of the block is set to the current item in the list for each
  110. iteration. In this way we can loop over collections.
  111. Template:
  112. {{#stooges}}
  113. <b>{{name}}</b>
  114. {{/stooges}}
  115. View:
  116. {
  117. "stooges": [
  118. { "name": "Moe" },
  119. { "name": "Larry" },
  120. { "name": "Curly" }
  121. ]
  122. }
  123. Output:
  124. <b>Moe</b>
  125. <b>Larry</b>
  126. <b>Curly</b>
  127. When looping over an array of strings, a `.` can be used to refer to the current
  128. item in the list.
  129. Template:
  130. {{#musketeers}}
  131. * {{.}}
  132. {{/musketeers}}
  133. View:
  134. {
  135. "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
  136. }
  137. Output:
  138. * Athos
  139. * Aramis
  140. * Porthos
  141. * D'Artagnan
  142. If the value of a section variable is a function, it will be called in the
  143. context of the current item in the list on each iteration.
  144. Template:
  145. {{#beatles}}
  146. * {{name}}
  147. {{/beatles}}
  148. View:
  149. {
  150. "beatles": [
  151. { "firstName": "John", "lastName": "Lennon" },
  152. { "firstName": "Paul", "lastName": "McCartney" },
  153. { "firstName": "George", "lastName": "Harrison" },
  154. { "firstName": "Ringo", "lastName": "Starr" }
  155. ],
  156. "name": function () {
  157. return this.firstName + " " + this.lastName;
  158. }
  159. }
  160. Output:
  161. * John Lennon
  162. * Paul McCartney
  163. * George Harrison
  164. * Ringo Starr
  165. #### Functions
  166. If the value of a section key is a function, it is called with the section's
  167. literal block of text, un-rendered, as its first argument. The second argument
  168. is a special rendering function that uses the current view as its view argument.
  169. It is called in the context of the current view object.
  170. Template:
  171. {{#bold}}Hi {{name}}.{{/bold}}
  172. View:
  173. {
  174. "name": "Tater",
  175. "bold": function () {
  176. return function (text, render) {
  177. return "<b>" + render(text) + "</b>";
  178. }
  179. }
  180. }
  181. Output:
  182. <b>Hi Tater.</b>
  183. ### Inverted Sections
  184. An inverted section opens with `{{^section}}` instead of `{{#section}}`. The
  185. block of an inverted section is rendered only if the value of that section's tag
  186. is `null`, `undefined`, `false`, or an empty list.
  187. Template:
  188. {{#repos}}<b>{{name}}</b>{{/repos}}
  189. {{^repos}}No repos :({{/repos}}
  190. View:
  191. {
  192. "repos": []
  193. }
  194. Output:
  195. No repos :(
  196. ### Comments
  197. Comments begin with a bang and are ignored. The following template:
  198. <h1>Today{{! ignore me }}.</h1>
  199. Will render as follows:
  200. <h1>Today.</h1>
  201. Comments may contain newlines.
  202. ### Partials
  203. Partials begin with a greater than sign, like {{> box}}.
  204. Partials are rendered at runtime (as opposed to compile time), so recursive
  205. partials are possible. Just avoid infinite loops.
  206. They also inherit the calling context. Whereas in ERB you may have this:
  207. <%= partial :next_more, :start => start, :size => size %>
  208. Mustache requires only this:
  209. {{> next_more}}
  210. Why? Because the `next_more.mustache` file will inherit the `size` and `start`
  211. variables from the calling context. In this way you may want to think of
  212. partials as includes, or template expansion, even though it's not literally true.
  213. For example, this template and partial:
  214. base.mustache:
  215. <h2>Names</h2>
  216. {{#names}}
  217. {{> user}}
  218. {{/names}}
  219. user.mustache:
  220. <strong>{{name}}</strong>
  221. Can be thought of as a single, expanded template:
  222. <h2>Names</h2>
  223. {{#names}}
  224. <strong>{{name}}</strong>
  225. {{/names}}
  226. In mustache.js an object of partials may be passed as the third argument to
  227. `Mustache.render`. The object should be keyed by the name of the partial, and
  228. its value should be the partial text.
  229. ### Set Delimiter
  230. Set Delimiter tags start with an equals sign and change the tag delimiters from
  231. `{{` and `}}` to custom strings.
  232. Consider the following contrived example:
  233. * {{ default_tags }}
  234. {{=<% %>=}}
  235. * <% erb_style_tags %>
  236. <%={{ }}=%>
  237. * {{ default_tags_again }}
  238. Here we have a list with three items. The first item uses the default tag style,
  239. the second uses ERB style as defined by the Set Delimiter tag, and the third
  240. returns to the default style after yet another Set Delimiter declaration.
  241. According to [ctemplates](http://google-ctemplate.googlecode.com/svn/trunk/doc/howto.html),
  242. this "is useful for languages like TeX, where double-braces may occur in the
  243. text and are awkward to use for markup."
  244. Custom delimiters may not contain whitespace or the equals sign.
  245. ## Streaming
  246. To stream template results out of mustache.js, you can pass an optional callback
  247. to the call to `Mustache.render`:
  248. Mustache.render(template, view, partials, function (chunk) {
  249. print(chunk);
  250. });
  251. When the template is finished rendering, the callback will be called with `null`
  252. after which it won't be called anymore for that rendering.
  253. ## Plugins for JavaScript Libraries
  254. By default mustache.js may be used in a browser or any [CommonJS](http://www.commonjs.org/)
  255. environment, including [node](http://nodejs.org/). Additionally, mustache.js may
  256. be built specifically for several different client libraries and platforms,
  257. including the following:
  258. - [jQuery](http://jquery.com/)
  259. - [MooTools](http://mootools.net/)
  260. - [Dojo](http://www.dojotoolkit.org/)
  261. - [YUI](http://developer.yahoo.com/yui/)
  262. - [RequireJS](http://requirejs.org/)
  263. - [qooxdoo](http://qooxdoo.org/)
  264. These may be built using [Rake](http://rake.rubyforge.org/) and one of the
  265. following commands:
  266. $ rake jquery
  267. $ rake mootools
  268. $ rake dojo
  269. $ rake yui
  270. $ rake requirejs
  271. $ rake qooxdoo
  272. ## Thanks
  273. Mustache.js wouldn't kick ass if it weren't for these fine souls:
  274. * Chris Wanstrath / defunkt
  275. * Alexander Lang / langalex
  276. * Sebastian Cohnen / tisba
  277. * J Chris Anderson / jchris
  278. * Tom Robinson / tlrobinson
  279. * Aaron Quint / quirkey
  280. * Douglas Crockford
  281. * Nikita Vasilyev / NV
  282. * Elise Wood / glytch
  283. * Damien Mathieu / dmathieu
  284. * Jakub Kuźma / qoobaa
  285. * Will Leinweber / will
  286. * dpree
  287. * Jason Smith / jhs
  288. * Aaron Gibralter / agibralter
  289. * Ross Boucher / boucher
  290. * Matt Sanford / mzsanford
  291. * Ben Cherry / bcherry
  292. * Michael Jackson / mjijackson