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

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