Jade模板引擎(一)之Attributes,jadeattributes
目錄:
- Attributes
- Boolean Attributes
- Style Attributes
- Class Attributes
- &Attributes
Attributes
jade中的屬性和html中的屬性並沒有什麼太大區別, 值也和js的規則沒有什麼兩樣。
1. js運算式
jade:
- var authenticated = truea(class=authenticated ? 'authed' : 'anon')
html:
<a class="authed"></a>
2. 多屬性換行
jade:
input( type='checkbox' name='agreement' checked)
html:
<input type="checkbox" name="argeement" checked="checked" />
3. 非轉義屬性(Unescaped Attributes)
預設情況下, 所有屬性都是轉義過的。這樣做是為了安全起見,防止XSS攻擊。如果需要使用特殊字元,可以使用"!="替代"="。
jade:
div(escaped="<code>")div(unescaped="<code>")
html:
<div escaped="<code>"></div><div unescaped="<code>"></div>
Boolean Attributes
在jade中, 屬性值可以是bool值(true or false), 不設定值則預設是true。
jade:
input(type='checkbox', checked)input(type='checkbox', checked=true)input(type='checkbox', checked=false)input(type='checkbox', checked=true.toString())
html:
<input type="checkbox" checked="checked" /><input type="checkbox" checked="checked" /><input type="checkbox" /><input type="checkbox" checked="true" />
Style Attributes
style屬性可以是一個string也可以是一個object。比如json格式的對象形式。
jade:
a(style={color: 'red', background:'green'})
html:
<a style="color:red;background:green"></a>
Class Attributes
class屬性可以是一個string也可以是一個定義的class的數組對象。
jade:
- var classes = ['foo', 'bar', 'baz']a(class=classes)a.bing(class=classes class=['bing'])
html:
<a class="foo bar baz"></a><a class="bing foo bar baz bing"></a>
同樣可以通過使用條件的形式來實現。
jade:
- var currentUrl = '/about'a(class={active: currentUrl === '/'} href='/') Homea(class={active: currentUrl === '/about'} href='/about') About
html:
<a href="/">Home</a><a href="/about" class="active">About</a>
&Attributes
&attributes可以將其兩邊的屬性對象都加入到元素當中。
jade:
- var attributes = {'data-foo': 'bar'}div#foo(data-bar='foo')&attributes(attributes)
html
<div id="foo" data-bar='foo' data-foo='bar'></div>
注: 在使用&attributes的情況下, 它並沒有實現自動轉義。所以需要通過一定的手段來確保你的頁面不會出現XSS漏洞。