JADEの記法について
基本的な変数の使い方は書いてあるけど、使っているうちにこんな時どうするの?って場面が結構あったので、メモしておきます。
基本
router.js
res.render("test",{title:'Hello'});
test.jade
p #{title}
p=title
結果
<p>Hello</p>
<p>Hello</p>
他の文字とつなげる
test.jade
p #{title}World
p=title+World
結果
<p>Helloworld</p>
<p>Helloworld</p>
これはだめ。エラーになる
test.jade
p=title world
エスケープしない
!= または !{} を使う
router.js
res.render("test",{title:"<span>Hello</span>"});
test.jade
p #{title}
p=title
p !{title}
p!=title
結果
<p><span>Hello</span></p>
<p><span>Hello</span></p>
<p><span>hello</span></p>
<p><span>hello</span></p>
配列に添え字でアクセス
router.js
var helloworld = ['Hello','World'];
res.render("test",{a:helloworld});
test.jade
p #{a[0]} #{a[1]}
結果
<p>Hello World</p>
連想配列にキー名でアクセス
router.js
var helloworld = {message1:'Hello',message2:'World'];
res.render("test",{a:helloworld});
test.jade
p #{a.message1} #{a.message2}
結果
<p>Hello World</p>
クラス名やIDを変数で指定する
router.js
res.render("test",{a:'myclass',b:'myid'});
test.jade
p(class=a)hoge
p(id=b)foo
結果
<p class="myclass">hoge</p>
<p class="myid">foo</p>