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

14 år sedan
16 år sedan
14 år sedan
Parser rewrite This commit is a complete rewrite of the core mustache.js file with two main goals: 1) a major performance boost and 2) better compliance with the mustache spec. In order to improve performance templates are pre-compiled to JavaScript functions. These compiled functions take a view, a partials object, and an optional callback as arguments. They are cached to prevent unnecessary re-compilation of an already compiled template. Both of these enhancements facilitate a generous boost in performance. A few other notes: - The mustache.js file is now both browser and CommonJS ready without any modification. - The API exposes two main methods: Mustache.compile and Mustache.render. The former is used to generate a function for a given template, while the latter is a higher-level function that is used to compile and render a template in one shot. Mustache.to_html is still available for backwards compatibility. - The concept of pragmas is removed to conform more closely to the original mustache spec. The dot symbol still works to reference the current item in an array. - The parser is much more strict about whitespace than it was before. The rule is simple: if a line contains only a non-variable tag (i.e. not {{tag}} or {{{tag}}}) and whitespace, that line is ignored in the output. Users may use the "space" option when compiling templates to preserve every whitespace character in the original template. - The parser is able to provide detailed information about where errors occur when parsing and rendering templates, including the line number and surrounding code context.
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
16 år sedan
14 år sedan
14 år sedan
14 år sedan
16 år sedan
14 år sedan
16 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
14 år sedan
16 år sedan
15 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
15 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
16 år sedan
14 år sedan
Parser rewrite This commit is a complete rewrite of the core mustache.js file with two main goals: 1) a major performance boost and 2) better compliance with the mustache spec. In order to improve performance templates are pre-compiled to JavaScript functions. These compiled functions take a view, a partials object, and an optional callback as arguments. They are cached to prevent unnecessary re-compilation of an already compiled template. Both of these enhancements facilitate a generous boost in performance. A few other notes: - The mustache.js file is now both browser and CommonJS ready without any modification. - The API exposes two main methods: Mustache.compile and Mustache.render. The former is used to generate a function for a given template, while the latter is a higher-level function that is used to compile and render a template in one shot. Mustache.to_html is still available for backwards compatibility. - The concept of pragmas is removed to conform more closely to the original mustache spec. The dot symbol still works to reference the current item in an array. - The parser is much more strict about whitespace than it was before. The rule is simple: if a line contains only a non-variable tag (i.e. not {{tag}} or {{{tag}}}) and whitespace, that line is ignored in the output. Users may use the "space" option when compiling templates to preserve every whitespace character in the original template. - The parser is able to provide detailed information about where errors occur when parsing and rendering templates, including the line number and surrounding code context.
14 år sedan
14 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 html = 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. ## Templates
  34. A [mustache](http://mustache.github.com/) template is a string that contains
  35. any number of mustache tags. Tags are indicated by the double mustaches that
  36. surround them. *{{person}}* is a tag, as is *{{#person}}*. In both examples we
  37. refer to *person* as the tag's key.
  38. There are several types of tags available in mustache.js.
  39. ### Variables
  40. The most basic tag type is a simple variable. A *{{name}}* tag renders the value
  41. of the *name* key in the current context. If there is no such key, nothing is
  42. rendered.
  43. All variables are HTML-escaped by default. If you want to render unescaped HTML,
  44. use the triple mustache: *{{{name}}}*. You can also use *&* to unescape a
  45. variable.
  46. Template:
  47. * {{name}}
  48. * {{age}}
  49. * {{company}}
  50. * {{{company}}}
  51. * {{&company}}
  52. View:
  53. {
  54. "name": "Chris",
  55. "company": "<b>GitHub</b>"
  56. }
  57. Output:
  58. * Chris
  59. *
  60. * &lt;b&gt;GitHub&lt;/b&gt;
  61. * <b>GitHub</b>
  62. * <b>GitHub</b>
  63. JavaScript's dot notation may be used to access keys that are properties of
  64. objects in a view.
  65. Template:
  66. * {{name.first}} {{name.last}}
  67. * {{age}}
  68. View:
  69. {
  70. "name": {
  71. "first": "Michael",
  72. "last": "Jackson"
  73. },
  74. "age": "RIP"
  75. }
  76. Output:
  77. * Michael Jackson
  78. * RIP
  79. ### Sections
  80. Sections render blocks of text one or more times, depending on the value of the
  81. key in the current context.
  82. A section begins with a pound and ends with a slash. That is, *{{#person}}*
  83. begins a *person* section, while *{{/person}}* ends it. The text between the two
  84. tags is referred to as that section's "block".
  85. The behavior of the section is determined by the value of the key.
  86. #### False Values or Empty Lists
  87. If the *person* key exists and has a value of `null`, `undefined`, or `false`,
  88. or is an empty list, the block will not be rendered.
  89. Template:
  90. Shown.
  91. {{#nothin}}
  92. Never shown!
  93. {{/nothin}}
  94. View:
  95. {
  96. "person": true,
  97. }
  98. Output:
  99. Shown.
  100. #### Non-Empty Lists
  101. If the *person* key exists and is not `null`, `undefined`, or `false`, and is
  102. not an empty list the block will be rendered one or more times.
  103. When the value is a list, the block is rendered once for each item in the list.
  104. The context of the block is set to the current item in the list for each
  105. iteration. In this way we can loop over collections.
  106. Template:
  107. {{#stooges}}
  108. <b>{{name}}</b>
  109. {{/stooges}}
  110. View:
  111. {
  112. "stooges": [
  113. { "name": "Moe" },
  114. { "name": "Larry" },
  115. { "name": "Curly" },
  116. ]
  117. }
  118. Output:
  119. <b>Moe</b>
  120. <b>Larry</b>
  121. <b>Curly</b>
  122. When looping over an array of strings, a `.` can be used to refer to the current
  123. item in the list.
  124. Template:
  125. {{#musketeers}}
  126. * {{.}}
  127. {{/musketeers}}
  128. View:
  129. {
  130. "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
  131. }
  132. Output:
  133. * Athos
  134. * Aramis
  135. * Porthos
  136. * D'Artagnan
  137. #### Functions
  138. If the value of a key is a function, it is called with the section's literal
  139. block of text, unrendered, as its first argument. The second argument is a
  140. special rendering function that uses the current view as its view argument. It
  141. is called in the context of the current view object.
  142. Template:
  143. {{#users}}
  144. {{#employee}}
  145. * {{email}}
  146. {{/employee}}
  147. {{/users}}
  148. View:
  149. {
  150. "domain": "example.com",
  151. "users": [
  152. { "handle": "joe", "employee": true },
  153. { "handle": "bob", "employee": false },
  154. { "handle": "jim", "employee": true }
  155. ],
  156. "employee": function () {
  157. this.
  158. },
  159. "email": function () {
  160. return function (text, render) {
  161. return this.handle + "@" + this.domain;
  162. }
  163. }
  164. }
  165. Output:
  166. * joe@example.com
  167. * bob@example.com
  168. * jim@example.com
  169. * Porthos
  170. * D'Artagnan
  171. TODO - pick up here
  172. Conditional sections begin with `{{#condition}}` and end with
  173. `{{/condition}}`. When `condition` evaluates to true, the section is rendered,
  174. otherwise the whole block will output nothing at all. `condition` may be a
  175. function returning true/false or a simple boolean.
  176. var view = {condition: function() {
  177. // [...your code goes here...]
  178. return true;
  179. }}
  180. {{#condition}}
  181. I will be visible if condition is true
  182. {{/condition}}
  183. ### Enumerable Sections
  184. Enumerable Sections use the same syntax as condition sections do.
  185. `{{#shopping_items}}` and `{{/shopping_items}}`. Actually the view decides how
  186. mustache.js renders the section. If the view returns an array, it will
  187. iterator over the items. Use `{{.}}` to access the current item inside the
  188. enumeration section.
  189. var view = {name: "Joe's shopping card",
  190. items: ["bananas", "apples"]}
  191. var template = "{{name}}: <ul> {{#items}}<li>{{.}}</li>{{/items}} </ul>"
  192. Outputs:
  193. Joe's shopping card: <ul><li>bananas</li><li>apples</li></ul>
  194. ### Higher Order Sections
  195. If a section key returns a function, it will be called and passed both the
  196. unrendered block of text and a renderer convenience function.
  197. Given this object:
  198. "name": "Tater",
  199. "bolder": function() {
  200. return function(text, render) {
  201. return "<b>" + render(text) + '</b>'
  202. }
  203. }
  204. And this template:
  205. {{#bolder}}Hi {{name}}.{{/bolder}}
  206. We'll get this output:
  207. <b>Hi Tater.</b>
  208. As you can see, we’re pre-processing the text in the block. This can be used
  209. to implement caching, filters (like syntax highlighting), etc.
  210. You can use `this.name` to access the attribute `name` from your view.
  211. ### Dereferencing Sections
  212. If your data has components that are logically grouped into nested objects,
  213. you may wish to dereference an object to access its values.
  214. Given this object:
  215. {
  216. "name": "Bill",
  217. "address": {
  218. "street": "801 Streetly street",
  219. "city": "Boston",
  220. "state": "MA",
  221. "zip" "02101"
  222. }
  223. }
  224. And this template:
  225. <h1>Contact: {{name}}</h1>
  226. {{#address}}
  227. <p>{{street}}</p>
  228. <p>{{city}}, {{state}} {{zip}}</p>
  229. {{/address}}
  230. We'll get this output:
  231. <h1>Contact: Bill</h1>
  232. <p>801 Streetly street</p>
  233. <p>Boston, MA 02101</p>
  234. ### Inverted Sections
  235. An inverted section opens with `{{^section}}` instead of `{{#section}}` and
  236. uses a boolean negative to evaluate. Empty arrays are considered falsy.
  237. View:
  238. var inverted_section = {
  239. "repo": []
  240. }
  241. Template:
  242. {{#repo}}<b>{{name}}</b>{{/repo}}
  243. {{^repo}}No repos :({{/repo}}
  244. Result:
  245. No repos :(
  246. ### View Partials
  247. mustache.js supports a quite powerful but yet simple view partial mechanism.
  248. Use the following syntax for partials: `{{>partial_name}}`
  249. var view = {
  250. name: "Joe",
  251. winnings: {
  252. value: 1000,
  253. taxed_value: function() {
  254. return this.value - (this.value * 0.4);
  255. }
  256. }
  257. };
  258. var template = "Welcome, {{name}}! {{>winnings}}"
  259. var partials = {
  260. winnings: "You just won ${{value}} (which is ${{taxed_value}} after tax)"};
  261. var output = Mustache.to_html(template, view, partials)
  262. output will be:
  263. Welcome, Joe! You just won $1000 (which is $600 after tax)
  264. You invoke a partial with `{{>winnings}}`. Invoking the partial `winnings`
  265. will tell mustache.js to look for a object in the context's property
  266. `winnings`. It will then use that object as the context for the template found
  267. in `partials` for `winnings`.
  268. ## Escaping
  269. mustache.js does escape all values when using the standard double mustache
  270. syntax. Characters which will be escaped: `& \ " ' < >`. To disable escaping,
  271. simply use triple mustaches like `{{{unescaped_variable}}}`.
  272. Example: Using `{{variable}}` inside a template for `5 > 2` will result in `5 &gt; 2`, where as the usage of `{{{variable}}}` will result in `5 > 2`.
  273. ## Streaming
  274. To stream template results out of mustache.js, you can pass an optional
  275. `send()` callback to the `to_html()` call:
  276. Mustache.to_html(template, view, partials, function(line) {
  277. print(line);
  278. });
  279. ## Pragmas
  280. Pragma tags let you alter the behaviour of mustache.js. They have the format
  281. of
  282. {{%PRAGMANAME}}
  283. and they accept options:
  284. {{%PRAGMANAME option=value}}
  285. ### IMPLICIT-ITERATOR
  286. When using a block to iterate over an enumerable (Array), mustache.js expects
  287. an objects as enumerable items. The implicit iterator pragma enables optional
  288. behaviour of allowing literals as enumerable items. Consider this view:
  289. var view = {
  290. foo: [1, 2, 3, 4, 5, "french"]
  291. };
  292. The following template can iterate over the member `foo`:
  293. {{%IMPLICIT-ITERATOR}}
  294. {{#foo}}
  295. {{.}}
  296. {{/foo}}
  297. If you don't like the dot in there, the pragma accepts an option to set your
  298. own iteration marker:
  299. {{%IMPLICIT-ITERATOR iterator=bob}}
  300. {{#foo}}
  301. {{bob}}
  302. {{/foo}}
  303. ## Plugins for JavaScript Libraries
  304. By default mustache.js may be used in a browser or any [CommonJS](http://www.commonjs.org/)
  305. environment, including [node](http://nodejs.org/). Additionally, mustache.js may
  306. be built specifically for several different client libraries and platforms,
  307. including the following:
  308. - [jQuery](http://jquery.com/)
  309. - [Dojo](http://www.dojotoolkit.org/)
  310. - [YUI](http://developer.yahoo.com/yui/)
  311. - [RequireJS](http://requirejs.org/)
  312. - [qooxdoo](http://qooxdoo.org/)
  313. These may be built using [Rake](http://rake.rubyforge.org/) and one of the
  314. following commands:
  315. $ rake jquery
  316. $ rake dojo
  317. $ rake yui
  318. $ rake requirejs
  319. $ rake qooxdoo
  320. ## Thanks
  321. Mustache.js wouldn't kick ass if it weren't for these fine souls:
  322. * Chris Wanstrath / defunkt
  323. * Alexander Lang / langalex
  324. * Sebastian Cohnen / tisba
  325. * J Chris Anderson / jchris
  326. * Tom Robinson / tlrobinson
  327. * Aaron Quint / quirkey
  328. * Douglas Crockford
  329. * Nikita Vasilyev / NV
  330. * Elise Wood / glytch
  331. * Damien Mathieu / dmathieu
  332. * Jakub Kuźma / qoobaa
  333. * Will Leinweber / will
  334. * dpree
  335. * Jason Smith / jhs
  336. * Aaron Gibralter / agibralter
  337. * Ross Boucher / boucher
  338. * Matt Sanford / mzsanford
  339. * Ben Cherry / bcherry
  340. * Michael Jackson / mjijackson