Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

14 лет назад
16 лет назад
11 лет назад
13 лет назад
13 лет назад
16 лет назад
13 лет назад
16 лет назад
13 лет назад
16 лет назад
14 лет назад
16 лет назад
14 лет назад
16 лет назад
10 лет назад
14 лет назад
16 лет назад
16 лет назад
11 лет назад
11 лет назад
16 лет назад
16 лет назад
16 лет назад
12 лет назад
16 лет назад
12 лет назад
16 лет назад
13 лет назад
16 лет назад
14 лет назад
16 лет назад
16 лет назад
16 лет назад
14 лет назад
16 лет назад
13 лет назад
16 лет назад
16 лет назад
12 лет назад
14 лет назад
16 лет назад
12 лет назад
12 лет назад
14 лет назад
12 лет назад
12 лет назад
14 лет назад
13 лет назад
14 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
13 лет назад
14 лет назад
13 лет назад
14 лет назад
14 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
13 лет назад
14 лет назад
13 лет назад
14 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
13 лет назад
14 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
13 лет назад
14 лет назад
12 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
13 лет назад
14 лет назад
12 лет назад
12 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
11 лет назад
12 лет назад
12 лет назад
14 лет назад
12 лет назад
14 лет назад
14 лет назад
12 лет назад
14 лет назад
16 лет назад
12 лет назад
16 лет назад
14 лет назад
14 лет назад
16 лет назад
14 лет назад
16 лет назад
13 лет назад
16 лет назад
14 лет назад
16 лет назад
12 лет назад
16 лет назад
14 лет назад
16 лет назад
12 лет назад
16 лет назад
16 лет назад
14 лет назад
16 лет назад
14 лет назад
14 лет назад
14 лет назад
16 лет назад
12 лет назад
16 лет назад
13 лет назад
16 лет назад
12 лет назад
16 лет назад
13 лет назад
16 лет назад
14 лет назад
16 лет назад
12 лет назад
16 лет назад
13 лет назад
16 лет назад
16 лет назад
14 лет назад
16 лет назад
12 лет назад
12 лет назад
12 лет назад
12 лет назад
14 лет назад
13 лет назад
14 лет назад
14 лет назад
14 лет назад
13 лет назад
14 лет назад
14 лет назад
14 лет назад
13 лет назад
14 лет назад
14 лет назад
14 лет назад
14 лет назад
10 лет назад
11 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. # mustache.js - Logic-less {{mustache}} templates with JavaScript
  2. > What could be more logical awesome than no logic at all?
  3. [![Build Status](https://travis-ci.org/janl/mustache.js.svg?branch=master)](https://travis-ci.org/janl/mustache.js) [![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.js](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 (AMD).
  11. And this will be your templates after you use Mustache:
  12. !['stache](https://cloud.githubusercontent.com/assets/288977/8779228/a3cf700e-2f02-11e5-869a-300312fb7a00.gif)
  13. ## Install
  14. You can get Mustache via [npm](http://npmjs.com).
  15. ```bash
  16. $ npm install mustache --save
  17. ```
  18. ## Command line tool
  19. mustache.js is shipped with a Node.js based command line tool. It might be installed as a global tool on your computer to render a mustache template of some kind
  20. ```bash
  21. $ npm install -g mustache
  22. $ mustache dataView.json myTemplate.mustache > output.html
  23. ```
  24. also supports stdin.
  25. ```bash
  26. $ cat dataView.json | mustache - myTemplate.mustache > output.html
  27. ```
  28. or as a package.json `devDependency` in a build process maybe?
  29. ```bash
  30. $ npm install mustache --save-dev
  31. ```
  32. ```json
  33. {
  34. "scripts": {
  35. "build": "mustache dataView.json myTemplate.mustache > public/output.html"
  36. }
  37. }
  38. ```
  39. ```bash
  40. $ npm run build
  41. ```
  42. The command line tool is basically a wrapper around `Mustache.render` so you get all the features.
  43. If your templates use partials you should pass paths to partials using `-p` flag:
  44. ```bash
  45. $ mustache -p path/to/partial1.mustache -p path/to/partial2.mustache dataView.json myTemplate.mustache
  46. ```
  47. ## Who uses mustache.js?
  48. An updated list of mustache.js users is kept [on the Github wiki](https://github.com/janl/mustache.js/wiki/Beard-Competition). Add yourself or your company if you use mustache.js!
  49. ## Contributing
  50. 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.
  51. ### Your First Contribution
  52. - review a [Pull Request](https://github.com/janl/mustache.js/pulls)
  53. - fix an [Issue](https://github.com/janl/mustache.js/issues)
  54. - update the [documentation](https://github.com/janl/mustache.js#usage)
  55. - make a website
  56. - write a tutorial
  57. * * *
  58. ## Usage
  59. Below is a quick example how to use mustache.js:
  60. ```js
  61. var view = {
  62. title: "Joe",
  63. calc: function () {
  64. return 2 + 4;
  65. }
  66. };
  67. var output = Mustache.render("{{title}} spends {{calc}}", view);
  68. ```
  69. 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.
  70. ## Templates
  71. 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.
  72. There are several techniques that can be used to load templates and hand them to mustache.js, here are two of them:
  73. #### Include Templates
  74. 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:
  75. ```js
  76. // file: render.js
  77. function renderHello() {
  78. var template = document.getElementById('template').innerHTML;
  79. var rendered = Mustache.render(template, { name: 'Luke' });
  80. document.getElementById('target').innerHTML = rendered;
  81. }
  82. ```
  83. ```html
  84. <html>
  85. <body onload="renderHello()">
  86. <div id="target">Loading...</div>
  87. <script id="template" type="x-tmpl-mustache">
  88. Hello {{ name }}!
  89. </script>
  90. <script src="https://unpkg.com/mustache@latest"></script>
  91. <script src="render.js"></script>
  92. </body>
  93. </html>
  94. ```
  95. #### Load External Templates
  96. If your templates reside in individual files, you can load them asynchronously and render them when they arrive. Another example using [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch):
  97. ```js
  98. function renderHello() {
  99. fetch('template.mustache')
  100. .then((response) => response.text())
  101. .then((template) => {
  102. var template = document.getElementById('template').innerHTML;
  103. var rendered = Mustache.render(template, { name: 'Luke' });
  104. document.getElementById('target').innerHTML = rendered;
  105. });
  106. }
  107. ```
  108. ### Variables
  109. 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.
  110. 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.
  111. If you'd like to change HTML-escaping behavior globally (for example, to template non-HTML formats), you can override Mustache's escape function. For example, to disable all escaping: `Mustache.escape = function(text) {return text;};`.
  112. If you want `{{name}}` _not_ to be interpreted as a mustache tag, but rather to appear exactly as `{{name}}` in the output, you must change and then restore the default delimiter. See the [Custom Delimiters](#custom-delimiters) section for more information.
  113. View:
  114. ```json
  115. {
  116. "name": "Chris",
  117. "company": "<b>GitHub</b>"
  118. }
  119. ```
  120. Template:
  121. ```
  122. * {{name}}
  123. * {{age}}
  124. * {{company}}
  125. * {{{company}}}
  126. * {{&company}}
  127. {{=<% %>=}}
  128. * {{company}}
  129. <%={{ }}=%>
  130. ```
  131. Output:
  132. ```html
  133. * Chris
  134. *
  135. * &lt;b&gt;GitHub&lt;/b&gt;
  136. * <b>GitHub</b>
  137. * <b>GitHub</b>
  138. * {{company}}
  139. ```
  140. JavaScript's dot notation may be used to access keys that are properties of objects in a view.
  141. View:
  142. ```json
  143. {
  144. "name": {
  145. "first": "Michael",
  146. "last": "Jackson"
  147. },
  148. "age": "RIP"
  149. }
  150. ```
  151. Template:
  152. ```html
  153. * {{name.first}} {{name.last}}
  154. * {{age}}
  155. ```
  156. Output:
  157. ```html
  158. * Michael Jackson
  159. * RIP
  160. ```
  161. ### Sections
  162. Sections render blocks of text one or more times, depending on the value of the key in the current context.
  163. 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".
  164. The behavior of the section is determined by the value of the key.
  165. #### False Values or Empty Lists
  166. 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.
  167. View:
  168. ```json
  169. {
  170. "person": false
  171. }
  172. ```
  173. Template:
  174. ```html
  175. Shown.
  176. {{#person}}
  177. Never shown!
  178. {{/person}}
  179. ```
  180. Output:
  181. ```html
  182. Shown.
  183. ```
  184. #### Non-Empty Lists
  185. 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.
  186. 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.
  187. View:
  188. ```json
  189. {
  190. "stooges": [
  191. { "name": "Moe" },
  192. { "name": "Larry" },
  193. { "name": "Curly" }
  194. ]
  195. }
  196. ```
  197. Template:
  198. ```html
  199. {{#stooges}}
  200. <b>{{name}}</b>
  201. {{/stooges}}
  202. ```
  203. Output:
  204. ```html
  205. <b>Moe</b>
  206. <b>Larry</b>
  207. <b>Curly</b>
  208. ```
  209. When looping over an array of strings, a `.` can be used to refer to the current item in the list.
  210. View:
  211. ```json
  212. {
  213. "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
  214. }
  215. ```
  216. Template:
  217. ```html
  218. {{#musketeers}}
  219. * {{.}}
  220. {{/musketeers}}
  221. ```
  222. Output:
  223. ```html
  224. * Athos
  225. * Aramis
  226. * Porthos
  227. * D'Artagnan
  228. ```
  229. 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.
  230. View:
  231. ```js
  232. {
  233. "beatles": [
  234. { "firstName": "John", "lastName": "Lennon" },
  235. { "firstName": "Paul", "lastName": "McCartney" },
  236. { "firstName": "George", "lastName": "Harrison" },
  237. { "firstName": "Ringo", "lastName": "Starr" }
  238. ],
  239. "name": function () {
  240. return this.firstName + " " + this.lastName;
  241. }
  242. }
  243. ```
  244. Template:
  245. ```html
  246. {{#beatles}}
  247. * {{name}}
  248. {{/beatles}}
  249. ```
  250. Output:
  251. ```html
  252. * John Lennon
  253. * Paul McCartney
  254. * George Harrison
  255. * Ringo Starr
  256. ```
  257. #### Functions
  258. 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.
  259. View:
  260. ```js
  261. {
  262. "name": "Tater",
  263. "bold": function () {
  264. return function (text, render) {
  265. return "<b>" + render(text) + "</b>";
  266. }
  267. }
  268. }
  269. ```
  270. Template:
  271. ```html
  272. {{#bold}}Hi {{name}}.{{/bold}}
  273. ```
  274. Output:
  275. ```html
  276. <b>Hi Tater.</b>
  277. ```
  278. ### Inverted Sections
  279. 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.
  280. View:
  281. ```json
  282. {
  283. "repos": []
  284. }
  285. ```
  286. Template:
  287. ```html
  288. {{#repos}}<b>{{name}}</b>{{/repos}}
  289. {{^repos}}No repos :({{/repos}}
  290. ```
  291. Output:
  292. ```html
  293. No repos :(
  294. ```
  295. ### Comments
  296. Comments begin with a bang and are ignored. The following template:
  297. ```html
  298. <h1>Today{{! ignore me }}.</h1>
  299. ```
  300. Will render as follows:
  301. ```html
  302. <h1>Today.</h1>
  303. ```
  304. Comments may contain newlines.
  305. ### Partials
  306. Partials begin with a greater than sign, like {{> box}}.
  307. Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops.
  308. They also inherit the calling context. Whereas in ERB you may have this:
  309. ```html+erb
  310. <%= partial :next_more, :start => start, :size => size %>
  311. ```
  312. Mustache requires only this:
  313. ```html
  314. {{> next_more}}
  315. ```
  316. 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, imports, template expansion, nested templates, or subtemplates, even though those aren't literally the case here.
  317. For example, this template and partial:
  318. base.mustache:
  319. <h2>Names</h2>
  320. {{#names}}
  321. {{> user}}
  322. {{/names}}
  323. user.mustache:
  324. <strong>{{name}}</strong>
  325. Can be thought of as a single, expanded template:
  326. ```html
  327. <h2>Names</h2>
  328. {{#names}}
  329. <strong>{{name}}</strong>
  330. {{/names}}
  331. ```
  332. 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.
  333. ```js
  334. Mustache.render(template, view, {
  335. user: userTemplate
  336. });
  337. ```
  338. ### Custom Delimiters
  339. Custom delimiters can be used in place of `{{` and `}}` by setting the new values in JavaScript or in templates.
  340. #### Setting in JavaScript
  341. The `Mustache.tags` property holds an array consisting of the opening and closing tag values. Set custom values by passing a new array of tags to `render()`, which gets honored over the default values, or by overriding the `Mustache.tags` property itself:
  342. ```js
  343. var customTags = [ '<%', '%>' ];
  344. ```
  345. ##### Pass Value into Render Method
  346. ```js
  347. Mustache.render(template, view, {}, customTags);
  348. ```
  349. ##### Override Tags Property
  350. ```js
  351. Mustache.tags = customTags;
  352. // Subsequent parse() and render() calls will use customTags
  353. ```
  354. #### Setting in Templates
  355. Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings.
  356. Consider the following contrived example:
  357. ```html+erb
  358. * {{ default_tags }}
  359. {{=<% %>=}}
  360. * <% erb_style_tags %>
  361. <%={{ }}=%>
  362. * {{ default_tags_again }}
  363. ```
  364. 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.
  365. According to [ctemplates](https://htmlpreview.github.io/?https://raw.githubusercontent.com/OlafvdSpek/ctemplate/master/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."
  366. Custom delimiters may not contain whitespace or the equals sign.
  367. ## Pre-parsing and Caching Templates
  368. 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`.
  369. ```js
  370. Mustache.parse(template);
  371. // Then, sometime later.
  372. Mustache.render(template, view);
  373. ```
  374. ## Plugins for JavaScript Libraries
  375. mustache.js may be built specifically for several different client libraries, including the following:
  376. - [jQuery](http://jquery.com/)
  377. - [MooTools](http://mootools.net/)
  378. - [Dojo](http://www.dojotoolkit.org/)
  379. - [YUI](http://developer.yahoo.com/yui/)
  380. - [qooxdoo](http://qooxdoo.org/)
  381. These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands:
  382. ```bash
  383. $ rake jquery
  384. $ rake mootools
  385. $ rake dojo
  386. $ rake yui3
  387. $ rake qooxdoo
  388. ```
  389. ## Testing
  390. In order to run the tests you'll need to install [Node.js](http://nodejs.org/).
  391. You also need to install the sub module containing [Mustache specifications](http://github.com/mustache/spec) in the project root.
  392. ```bash
  393. $ git submodule init
  394. $ git submodule update
  395. ```
  396. Install dependencies.
  397. ```bash
  398. $ npm install
  399. ```
  400. Then run the tests.
  401. ```bash
  402. $ npm test
  403. ```
  404. 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:
  405. 1. Create a template file named `mytest.mustache` in the `test/_files`
  406. directory. Replace `mytest` with the name of your test.
  407. 2. Create a corresponding view file named `mytest.js` in the same directory.
  408. This file should contain a JavaScript object literal enclosed in
  409. parentheses. See any of the other view files for an example.
  410. 3. Create a file with the expected output in `mytest.txt` in the same
  411. directory.
  412. Then, you can run the test with:
  413. ```bash
  414. $ TEST=mytest npm run test-render
  415. ```
  416. ### Browser tests
  417. Browser tests are not included in `npm test` as they run for too long, although they are ran automatically on Travis when merged into master. Run browser tests locally in any browser:
  418. ```bash
  419. $ npm run test-browser-local
  420. ```
  421. then point your browser to `http://localhost:8080/__zuul`
  422. ### Troubleshooting
  423. #### npm install fails
  424. Ensure to have a recent version of npm installed. While developing this project requires npm with support for `^` version ranges.
  425. ```bash
  426. $ npm install -g npm
  427. ```
  428. ## Thanks
  429. mustache.js wouldn't kick ass if it weren't for these fine souls:
  430. * Chris Wanstrath / defunkt
  431. * Alexander Lang / langalex
  432. * Sebastian Cohnen / tisba
  433. * J Chris Anderson / jchris
  434. * Tom Robinson / tlrobinson
  435. * Aaron Quint / quirkey
  436. * Douglas Crockford
  437. * Nikita Vasilyev / NV
  438. * Elise Wood / glytch
  439. * Damien Mathieu / dmathieu
  440. * Jakub Kuźma / qoobaa
  441. * Will Leinweber / will
  442. * dpree
  443. * Jason Smith / jhs
  444. * Aaron Gibralter / agibralter
  445. * Ross Boucher / boucher
  446. * Matt Sanford / mzsanford
  447. * Ben Cherry / bcherry
  448. * Michael Jackson / mjackson
  449. * Phillip Johnsen / phillipj
  450. * David da Silva Contín / dasilvacontin