Webブラウザ上で動く JavaScript の話。

RequireJS で使える tpl.js プラグイン GitHub - JulienCabanes/requirejs-tpl: RequireJS Template PluginUnderscore.js と同じテンプレート機能を実装しているとのこと。

tpl.js プラグインを利用して、 HTML のテンプレートファイル (*.tpl) に JavaScript から値を埋め込んで表示してみるサンプルを書いてみる。

ファイル構成。


├── hoge.tpl
├── index.html
├── libs
│   └── tpl.js
├── main.js
└── require.js

index.html

RequireJS を使って main.js を読み込む。


<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>RequireJS: sample</title>
  <!-- data-main attribute tells require.js to load
       scripts/main.js after require.js loads. -->
  <script data-main="main" src="require.js"></script>
</head>
<body>
<h1>RequireJS: sample</h2>
<div id="hoge"></div>
</body>
</html>

main.js

GitHub - JulienCabanes/requirejs-tpl: RequireJS Template Plugin からダウンロードした tpl.js プラグインのパスを指定。

「tpl!」で指定した hoge.tpl ファイルを読み込んで、 index.html の中に埋め込む。その際に JavaScript オブジェクトを指定し、 message プロパティに 「hello, world」の文字列を設定しておく。


require.config({
  paths: {
    'tpl': 'libs/tpl'
  }
});

require(
  ['tpl!hoge.tpl'],
  function(hogeTpl) {
 
  document.getElementById('hoge').innerHTML = hogeTpl({message: 'hello, world'});
  console.log(hogeTpl);
});

hoge.tpl

読み込むテンプレートファイル。


<p>message: <%= message %></p>

tpl.js プラグインは XMLHttpRequest でファイルを取得しているので、テンプレートファイルを取得する際には HTTP 通信が発生している。たくさんのテンプレートファイルを読み込むと処理に時間がかかるかもしれないので注意。

サンプルコードはこちら ⇒ RequireJS: sample

tags: javascript

Posted by NI-Lab. (@nilab)