RequireJSにてtextプラグインを利用する
Backbone.js とか利用していると template を外に出すと思う。 RequireJS には text プラグインという、まさに temlate 用に作成されたプラグインがある。
サンプルの為に Mustache.js を利用して、その利用法を記載する。
text プラグインとは
text リソースの読み込み用のプラグイン。RequireJS にて、dependency names に読み込む template を text!foobarbaz.html として書けるので、 template の読み込みにとても便利。(説明を見る限り、最適化する際は template の文言をインライン展開するみたい、確認はしていませんが。)
Load text files and treat them as dependencies. Great for loading templates. The text strings can be inlined in an optimized build when the optimizer is used.
Download RequireJS - Plugins - text
ディレクトリ構成例
今回は scripts/libs 配下に必要なライブラリを格納した。text プラグインは こちらのページ の Download ボタンからダウンロードして配置すること。
$ tree . ├── index.html └── scripts ├── config.js ├── libs │   ├── jquery-1.8.2.min.js # jQuery │   ├── mustache.js # Mustache.js │   ├── require.js # RequireJS │   └── text.js # RequireJS text plugin ├── main.js └── temp └── home.html
サンプルコード
scripts/temp/home.html
以下の内容を Mustache.js でパースして表示する。
<h1>template から読み取れた!</h1> <p>{{ message }}</p>
scripts/main.js
text! で読み込み対象を指定できる。便利。
require( // text!(template の path) として template を読み込む ['jquery', 'mustache', 'text!temp/home.html'], function($, Mustache, template) { // template を Mustache でパースする際の data var data = { message: 'このように変数も出力可能' }; // Mustache.to_html() でパースする。 // パースした結果を、#contents の中身へ出力する。 $('#contents').html( Mustache.to_html(template, data) ); });
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>RequireJS text Plugin Sample.</title> </head> <body> <div id="contents"></div> <!-- scripts --> <script src="scripts/config.js"></script> <script data-main="main" src="scripts/libs/require.js"></script> </body> </html>
scripts/config.js
var require = { baseUrl: 'scripts/', urlArgs: 'bust=' + (new Date()).getTime(), shim: { 'jquery': { exports: '$' }, 'mustache': { exports: 'Mustache' } }, paths: { jquery: 'libs/jquery-1.8.2.min', text: 'libs/text', mustache: 'libs/mustache' } };