Node.jsで使えるテンプレートエンジンライブラリ、mustache.jsの使い方についてです。プログラミングにおいて、テンプレートエンジンは様々なシーン、例えばウェブアプリケーションのMVCにおけるV、ビューや、テキストデータやプログラムの生成など、で利用機会があります。
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 ) ;
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>
<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 ) ;
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.
{{=<% %>=}}
でデリミタを<% %>
に変更しています。それを<%={{ }}=%>
で{{ }}
へ戻しています。
Custom delimiter inside template:
* {{ title }}
* Joe
{{==}}
* {{ title }}
* Joe
* Joe
* <% title %>
janl/mustache.js: Minimal templating with {{mustaches}} in JavaScript