Friday, 22 June 2012

nodejs - express

express

初歩の初歩
参考:
http://blog.twiwt.org/e/30ebba


ejsとjade
テンプレートエンジンとして主にjadeとejsがある。 ejsの方が、htmlと同じ感覚で書いていける。

デフォルトはjadeになっているので、ejsでテンプレートを作るときは、

$ express -s -t ejs project_name

とする。

参考:
http://memo.yomukaku.net/entries/279
http://r.otsuya.co/post/13378772401/node-express-ejs


expressで作成されるテンプレの中身で主にいじるファイル

- app.js
サーバーサイドのjs。テンプレで作成したものの下に追記していくかんじ。

- views/layout.ejs
普段、index.htmlの役目を果たすもの。

- views/index.ejs
テンプレ状態では、layout.ejsのbody内に、このファイルの内容が書き込まれる

- public/javascripts/ に作成するjsファイル (client.jsなど適当に名前を付ける)
クライアントサイドのjs。
layout.ejsのhead内から、
<script src="/javascripts/client.js"</script>
などとして読み込む

- routes/index.js
テンプレでは、app.js内の、
app.get('/', routes.index);
から投げられた先として、
exports.index = function(req, res){
     res.render('index', {
          title: 'my title'
     });
};
を実行する。
res.render('', {});
の第二引数のオブジェクトに、
title: 'my title'
message: 'hello'
などといれると、index.ejs内の
<%=title %>
<%=message %>
に渡される。

ちなみに、app.jsで、
app.get('/', routes.index);
と書かずに、
app.get('/', function(req, res){}
とすれば、index.jsに渡さずに書ける。

No comments:

Post a Comment