Node.js

mustache.js入門・Node.jsのテンプレートエンジンmustache.jsの使い方

https://yuis.xsrv.jp/data/uJFu1RpJxAl3cv1CYfrf7DTDRZOUmtgP.png

janl/mustache.js: Minimal templating with {{mustaches}} in JavaScript

インストール

npm install mustache --save

require

var fs = require('fs');
var path = require('path');

var Mustache = require('mustache');

基本の使用例

var view = {
  title: "Joe",
  calc: function () {
    return 2 + 4;
  }
};

template = `
basic usage: {{title}} spends {{calc}}
`;

var output = Mustache.render(template, view);

log( output ) ;

https://yuis.xsrv.jp/images/ss/ShareX_ScreenShot_5d2270ac-7af4-41d3-ae16-b42dc090dc4a.png

basic usage: Joe spends 6

if

{{#NOTEFILE}}
  note file found.
    {{NOTEFILE}}
{{/NOTEFILE}}

!if

{{^NOTEFILE}}
    no note file found.
{{/NOTEFILE}}

コメント


<header class='split-view-inspector-header'> <div class="view-title">Source Assets</div> {{! <div class="actions"> commented <span class="label">Actions</span> <span class="gear"></span> </div> }} </header>

https://yuis.xsrv.jp/images/ss/ShareX_ScreenShot_0bac97fc-05ea-4a10-88bf-8f678664e142.png

<header class='split-view-inspector-header'>
    <div class="view-title">Source Assets</div>
</header>

カスタムデリミタ


template = ` Custom Delimiters: <% title %> `; var customTags = [ '<%', '%>' ]; Mustache.tags = customTags; output = Mustache.render(template, view, {}, customTags); log( output ) ;

https://yuis.xsrv.jp/images/ss/ShareX_ScreenShot_f2df692f-ac1a-4621-9b3c-b74bd80b11c1.png

Custom Delimiters: Joe

カスタムデリミタ(テンプレートの中で変更する)


template = ` Custom delimiter inside template: * {{ title }} * <% title %> {{=<% %>=}} * {{ title }} * <% title %> <%={{ }}=%> * {{ title }} * <% title %> ` ; var output = Mustache.render(template, view); log( output ) ;

Set Delimiter tags start with an equals sign and change the tag delimiters from {{ and }} to custom strings.

{{=<% %>=}}でデリミタを<% %>に変更しています。それを<%={{ }}=%>{{ }}へ戻しています。

https://yuis.xsrv.jp/images/ss/ShareX_ScreenShot_16f3cd51-d8b0-44b2-8f08-5eb2f0fabd11.png

Custom delimiter inside template:

* {{ title }}
* Joe
{{==}}
* {{ title }}
* Joe
* Joe
* <% title %>

janl/mustache.js: Minimal templating with {{mustaches}} in JavaScript