まずはプロジェクトフォルダを作成しておきましょう。
$ mkdir hello-world-ejs $ cd hello-world-ejs
package.jsonを作成
package.jsonを作成します。
$ touch package.json
{
"name": "hello-world-ejs",
"description": "hello world EJS test app",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.x",
"ejs": "*"
}
}使用モジュールをインストール
$ npm install
Viewを作成
テンプレートファイル(view)を作ります。
$ mkdir views $ touch header.html $ touch users.html $ touch footer.html
header.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
<%=title %>
</title>
</head>
<body>users.html
<% include header.html %>
<h1>Users</h1>
<ul id="users">
<% users.forEach(function(user){ %>
<li><%= user.name %> <<%= user.email %>></li>
<% }) %>
</ul>
<% include footer.html %>footer.html
</body> </html>
app.jsを作成
/**
* Module dependencies.
*/
var express = require('express');
var app = express();
// Register ejs as .html. If we did
// not call this, we would need to
// name our views foo.ejs instead
// of foo.html. The __express method
// is simply a function that engines
// use to hook into the Express view
// system by default, so if we want
// to change "foo.ejs" to "foo.html"
// we simply pass _any_ function, in this
// case `ejs.__express`.
app.engine('.html', require('ejs').__express);
// Optional since express defaults to CWD/views
app.set('views', __dirname + '/views');
// Without this you would need to
// supply the extension to res.render()
// ex: res.render('users.html').
app.set('view engine', 'html');
// Dummy users
var users = [
{
name: 'xxx',
email: 'xxx@hoge'
},
{
name: 'yyy',
email: 'yyy@foo'
},
{
name: 'zzz',
email: 'zzz@baa'
}
];
app.get('/', function (req, res) {
res.render('users', {
users: users,
title: "EJS example"
});
});
if (!module.parent) {
app.listen(3000);
console.log('Express app started on port 3000');
}アプリ起動
$ nodejs app.js
Express app started on port 3000http://localhost:3000 にアクセスするとダミーのユーザ一覧が表示されます。
参考にしたページ
visionmedia/express · GitHub
関連ページ
Nodejs+ExpressでRedisを使うサンプル。
Node.js+ExpressなHelloWorld
0 件のコメント:
コメントを投稿