今回の環境。

OS: Mac OS X Yosemite 10.10.2

Node.js はインストール済み。


$ node --version
v0.10.29

npm install で swig モジュールと express モジュールをインストールする。


$ npm install swig
swig@1.4.2 node_modules/swig
├── optimist@0.6.1 (wordwrap@0.0.2, minimist@0.0.10)
└── uglify-js@2.4.19 (uglify-to-browserify@1.0.2, async@0.2.10, source-map@0.1.34, yargs@3.5.4)

$ npm install express
express@4.12.3 node_modules/express
├── merge-descriptors@1.0.0
├── utils-merge@1.0.0
├── cookie-signature@1.0.6
(以下略)

今回のサンプルは、テンプレートファイルとJSファイルの2ファイルを用意。

テンプレートファイル。


$ cat template.html 
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
{% for number in numbers -%}
{{ number }}
{%- endfor %}
</body>
</html>

JavaScript によるサンプルコード。


$ cat ./sample.js

var express = require('express');
var swig = require('swig');

// express と swig をつなぐ設定
// 参考: http://expressjs.com/api.html
var app = express();
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.set('view cache', false);
swig.setDefaults({ cache: false });

// リクエストを受ける
app.get('/', function(req, res){
  var data = {
    title : "Express.js with Swig",
    numbers : [1, 2, 3, 4, 5]
  };
  res.render('template.html', data);
});

app.listen(1337);
console.log('Application Started on http://localhost:1337/');
console.log('__dirname: ' + __dirname);

node を実行。 Web サーバが起動する。


$ node ./sample.js 
Application Started on http://localhost:1337/
__dirname: /Users/hoge/node

別のターミナルを起動して curl などでアクセスすると、 Express + Swig による出力を見ることができる。


$ curl http://localhost:1337/
<html>
<head>
<title>Express.js with Swig</title>
</head>
<body>
12345
</body>
</html>

tags: node.js express swig template_engine

Posted by NI-Lab. (@nilab)