Jade之属性

时间:2023-03-10 04:39:07
Jade之属性

属性

所有的html(5)标签在jade中均支持如下写法。jade中省去了html<>和标签的关闭等写法,并将属性写在括号之中。若存在多个属性,可以将其分为多行。

jade:

a(href='google.com') Google
a(class='button', href='google.com') Google input(
type='checkbox'
name='agreement'
checked
)

html:

<a href="google.com">Google</a>
<a href="google.com" class="button">Google</a> <input type="checkbox" name="agreement" checked="checked"/>

对于正常的javascript表达式,jade也可以应付。

jade:

- var authenticated = true
body(class=authenticated ? 'authed' : 'anon')

html:

<body class="authed"></body>

特殊属性

对于某些特殊符号,比如<,>等等,在jade编译生成html后,将会变成&lt;,&gt;,所以对于此类符号采取如下写法。

jade:

div(escaped="<code>")
div(unescaped!="<code>")

html:

<div escaped="&lt;code&gt;"></div>
<div unescaped="<code>"></div>

布尔型属性

某些属性在jade中接受bool值(false的话则在编译后生成的html中无该属性),无初值默认为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属性

通过JS可以将style属性封装在一个类中,也可以将style属性的值赋为一个字符串。

jade:

a(style={color: 'red', background: 'green'})

html:

<a style="color:red;background:green"></a>

class属性

class属性支持数组赋值。

jade:

//- 预定义数组后赋值
- var classes = ['foo', 'bar', 'baz']
a(class=classes) //- 无名数组
a(class=['bing', 'bat']) //- 多个属性值,可以合并,并且不去重
a.baz(class=classes class=['bing', 'bar'])

html:

<a class="foo bar baz"></a>

<a class="bing bat"></a>

<a class="baz foo bar baz bing bar"></a>

class、id

因为class属性和id属性会经常使用到,所以jade允许简化写法。

对于class可以直接.value表示class="value",对于id可以直接#value表示id="value"

因为div也会经常用到,jade允许div可以省去。

jade:

a.button

.content

html:

<a class="button"></a>

<div class="content"></div>

&attributes

&attributes(作用?)可以添加一个对象作为属性(可以为对象变量)的一部分。

jade:

div#foo(data-bar="foo")&attributes({'data-foo': 'bar'})

- var attributes = {'data-foo': 'bar'};
div#foo(data-bar="foo")&attributes(attributes)

html:

<div id="foo" data-bar="foo" data-foo="bar"></div>

<div id="foo" data-bar="foo" data-foo="bar"></div>

因为使用了&attributes的属性不会自动逃逸,所以为了防止cross-site scripting,请保证用户输入合法。