返回 导航

HTML5 / CSS3

hangge.com

Template7 - 表达式介绍1(if、else、unless)

作者:hangge | 2016-09-01 08:45
Template7 提供了丰富的表达式语法(Expressions syntax)供我们使用,本文介绍其中的 {{#if}}...{{else}}...{{/if}}{{#unless}}...{{else}}...{{/unless}} 这2个表达式。

一、{{#if}}...{{else}}...{{/if}}
{{#if}} 判断数据是否不是 false(或者不为 "undefined" 或 "null" 或"" 或"0")。不是 false 的话则走 {{#if}},否则走 {{else}} 分支。
1,单独使用if
(1)假设上下文数据
{
  active: true,
  title: 'Link',
}
(2)模板样例
<a href="#" {{#if active}}class="active"{{/if}}>{{title}}</a> 
(3)输出结果
<a href="#" class="active">Link</a>

2,if与else配合使用
(1)假设上下文数据
{
  name: 'John Doe',
  hobby: false
}
(2)模板样例
<p>Hello, my name is {{name}}.</p>
{{#if hobby}}
<p>I have hobby</p>
{{else}}
<p>I don't have hobby</p>
{{/if}} 
(3)输出结果
<p>Hello, my name is John Doe.</p>
<p>I don't have hobby</p>

二、{{#unless}}...{{else}}...{{/unless}}
{{#unless}} 同上面的 {{#if}} 表达式正好相反。判断数据是不是 false(或者是 "undefined" 或 "null" 或"" 或"0")。是 false 的话则走 {{#unless}},否则走 {{else}} 分支。
1,单独使用unless
(1)假设上下文数据
{
  active: true,
  title: 'Link',
}
(2)模板样例
<a href="#" {{#unless active}}class="active"{{/unless}}>{{title}}</a>
(3)输出结果
<a href="#">Link</a>

2,unless与else配合使用
(1)假设上下文数据
{
  name: 'John Doe',
  hobby: false
}
(2)模板样例
<p>Hello, my name is {{name}}.</p>
{{#unless hobby}}
<p>I have hobby</p>
{{else}}
<p>I don't have hobby</p>
{{/unless}}   
(3)输出结果
<p>Hello, my name is John Doe.</p>
<p>I have hobby</p>

评论

全部评论(0)

回到顶部