Template7学习记录

来源:http://idangero.us/template7/#.V2iXqJGF6Ul

测试用json数据:

var jsonData = {
            people: [
              {
                  firstName: 'John',
                  lastName: 'Doe'
              },
              {
                  firstName: 'Mark',
                  lastName: 'Johnson'
              },
            ],
            title: "this is a test title",
            preKey: "full name"
        };

template7支持下面的语法:

变量:

{{title}}:输出当前上下文对象下的title字段

{{../title}}:输出当前上下文对象的父级对象下的title字段

{{../../title}}:输出当前上下文对象向上推两级的对象下的title字段

{{this}}:当前上下文对象

{{person.name}}:输出在当前上下文中的“人”变量的“名称”属性

{{../person.name}}:输出在当前上下文的 父级对象 中的“人”变量的“名称”属性

块表达式:

{{#each}} :循环开始

{{else}}:当数组无数据的时候执行

{{/each}}:结束循环

{{if}}:条件判断

{{else}}:不满足条件判断执行块

{{/if}}:结束

{{#each reverse="true"}} - begin of block expression with passed reverse:true hash arguments,暂没用过,也没翻译

  

编辑和渲染:

template7是全球可用的窗口函数。
首先,我们需要提供字符串模板。例如,我们可以存储在脚本标签中。

下面一个例子:每一步注释都写的很清楚了。

@*引入js*@
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/Template7-1.1.0/src/template7.js"></script>
<script>
    $(function () {
        //测试用json数据
        var jsonData = {
            people: [
              {
                  firstName: 'John',
                  lastName: 'Doe'
              },
              {
                  firstName: 'Mark',
                  lastName: 'Johnson'
              },
            ],
            title: "this is a test title",
            preKey: "full name"
        };

        //获取模板
        var template = $('#template').html();

        // 编译模板
        var compiledTemplate = Template7.compile(template);

        // 使用模板加载数据
        var htmlStr = compiledTemplate(jsonData);

        //将得到的结果输出到指定区域
        $("#contents").html(htmlStr);
    });


</script>
@*模板的 type指定为 text/template7 *@
<script type="text/template7" id="template">
    <p>{{title}}</p>
    <ul>
        {{#each people}}
        <li>{{../preKey}}:{{firstName}} {{lastName}}</li>
        {{/each}}
    </ul>
</script>

<div id="contents"></div>

 内置函数:

{{join myArray delimiter=", "}}:把数组 myArray 的每个元素使用逗号“,”拼接到一起。只为数组

{{@index}}:在循环中,获得序号,从0开始。只为数组

@first:循环中的第一个项。只为数组

@last:循环中的最后一个项。只为数组

@key:当前对象属性的名称。只为对象

Template 模板Context 数据Output 输出
Iterate through Array items 遍历数组项
<p>Here are the list of people i know:</p>
<ul>
  {{#each people}}
  <li>{{firstName}} {{lastName}}</li>
  {{/each}}    
</ul>          
{
  people : [
    {
      firstName: 'John',
      lastName: 'Doe'
    },
    {
      firstName: 'Mark',
      lastName: 'Johnson'
    },
  ]
}      
<p>Here are the list of people i know:</p>
<ul>
  <li>John Doe</li>
  <li>Mark Johnson</li>
</ul>    
<p>Here are the list of people i know:</p>
<ul>
  {{#each people}}
  <li>{{@index}}. {{this}}</li>
  {{/each}}    
</ul>          
{
  people : ['John Doe', 'Mark Johnson']
}      
<p>Here are the list of people i know:</p>
<ul>
  <li>0. John Doe</li>
  <li>1. Mark Johnson</li>
</ul>  
Iterate through Object properties
<p>Car properties:</p>
<ul>
  {{#each props}}
  <li>{{@key}}: {{this}}</li>
  {{/each}}
</ul>
{
  props: {
    power: '150 hp',
    speed: '200 km/h',
  }
}
<p>Car properties:</p>
<ul>
  <li>power: 150 hp</li>
  <li>speed: 200 kn/h</li>
</ul>
{{else}} expression.
<p>Car properties:</p>
<ul>
  {{#each props}}
  <li>{{@key}}: {{this}}</li>
  {{else}}
  <li>No properties</li>
  {{/each}}
</ul>
{
  props: {
    power: '150 hp',
    speed: '200 km/h',
  }
}
<p>Car properties:</p>
<ul>
  <li>power: 150 hp</li>
  <li>speed: 200 kn/h</li>
</ul>
<p>Car properties:</p>
<ul>
  {{#each props}}
  <li>{{@key}}: {{this}}</li>
  {{else}}
  <li>No properties</li>
  {{/each}}
</ul>
{}
<p>Car properties:</p>
<ul>
  <li>No properties</li>
</ul>

{#if}}...{{else}}...{{/if}}

Template 模板Context 数据Output 输出
<a href="#" {{#if active}}class="active"{{/if}}>{{title}}</a>
{
  active: true,
  title: 'Link',
}
<a href="#" class="active">Link</a>
{{else}} expression.
<p>Hello, my name is {{name}}.</p>
{{#if hobby}}
<p>I have hobby</p>
{{else}}
<p>I don't have hobby</p>
{{/if}}                  
{
  name: 'John Doe',
  hobby: false
}
<p>Hello, my name is John Doe.</p>
<p>I don't have hobby</p>

 

{{#unless}}...{{else}}...{{/unless}}

Template ->Context ->Output
<a href="#" {{#unless active}}class="active"{{/unless}}>{{title}}</a>
{
  active: true,
  title: 'Link',
}
<a href="#">Link</a>
{{else}} expression.
<p>Hello, my name is {{name}}.</p>
{{#unless hobby}}
<p>I have hobby</p>
{{else}}
<p>I don't have hobby</p>
{{/unless}}                  
{
  name: 'John Doe',
  hobby: false
}
<p>Hello, my name is John Doe.</p>
<p>I have hobby</p>

{{#with}}...{{/with}}

Template ->Context ->Output
{{#with props}}
<p>Car has {{power}} power and {{speed}} maximum speed</p>
{{/with}}
{
  props: {
    power: '150 hp',
    speed: '200 km/h',
  }
}
<p>Car has 150 hp power and 200 km/h maximum speed</p>

 

{{#variableName}}...{{/variableName}}

Template ->Context ->Output
<ul>
  {{#people}}
  <li>{{name}} - {{age}} years old</li>
  {{/people}}
</ul>
{
  people: [
    {
      name: 'John Doe',
      age: 18
    },
    {
      name: 'Mark Johnson',
      age: 21
    }
  ]  
}
<ul>
  <li>John Doe - 18 years old</li>
  <li>Mark Johnson - 21 years old</li>
</ul>
{{#props}}
<p>Car has {{power}} power and {{speed}} maximum speed</p>
{{/props}}
{
  props: {
    power: '150 hp',
    speed: '200 km/h',
  }
}
<p>Car has 150 hp power and 200 km/h maximum speed</p>

 {{join delimiter=""}}

Template ->Context ->Output
<h3>"{{title}}" TV Show</h3>
<p>Was released in year {{year}}</p>
<p>Genres: {{join genres delimiter=", "}}</p>
{
  title: 'Friends',
  year: 2001,
  genres: ['comedy', 'drama']
}
<h3>"Friends" TV Show</h3>
<p>Was released in year 2001</p>
<p>Genres: comedy, drama</p>

{{escape}}

Template ->Context ->Output
<h1>{{title}}</h1>
<p>{{escape body}}</p>
{
  title: 'Paragraphs',
  body: 'We need to use <p> tags to add paragraphs in HTML',
}
<h1>Paragraphs</h1>
<p>We need to use &lt;p&gt; tags to add paragraphs in HTML</p>

 

{{js "expression"}}

Template ->Context ->Output
<h3>{{title}}</h3>
<p>Price: ${{js "this.price * 1.2"}} </p>
<p>{{js "this.inStock ? 'In Stock' : 'Not in stock'"}} </p>
{
  title: 'iPhone 6 Plus',
  price: 1000,
  inStock: true
}
<h3>iPhone 6 Plus</h3>
<p>Price: $1200</p>
<p>In stock</p>

{{#js_compare "expression"}}...{{/js_compare}}

Template ->Context ->Output
<h3>{{title}}</h3>
<p>Price: ${{price}} </p>
<p>{{#js_compare "color === 'white' && memory > 16"}}Not in stock{{else}}In stock{{/js_compare}} </p>
{
  title: 'iPhone 6 Plus',
  price: 1000,
  color: 'white',
  memory: 32
}
<h3>iPhone 6 Plus</h3>
<p>Price: $1000</p>
<p>Not in stock</p>
<p>{{#js_compare "a === b"}}A equals to B{{else}}A not equal to B{{/js_compare}} </p>
{
  a: 5,
  b: 34
}
<p>A not equal to B</p>

Using Custom Helpers,自定义函数

语法:

Template7.registerHelper(name, helper)

  • name - string - helper name
  • helper - function - helper function to handle passed context

Demo:

Template7.registerHelper('link', function (url, title, options){
  var ret = '<li>' +
              '<a href="' + url + '" class="item-content item-link" target="' + options.hash.target + '">' +
                '<div class="item-inner">' +
                  '<div class="item-title">' + title + '</div>' +
                '</div>' +
              '</a>' +
            '</li>';
  return ret;
});

  

Template ->Context ->Output
<div class="list-block">
  <ul>
    {{#each links}}
    {{link url title target="_blank"}}
    {{/each}}    
  </ul>
</div>
{
  links: [
    {
      url: 'http://google.com',
      title: 'Google'
    },
    {
      url: 'http://idangero.us',
      title: 'iDangero.us'
    },
  ]
}
<div class="list-block">
  <ul>
    <li>
      <a href="http://google.com" target="_blank" class="item-link item-content">
        <div class="item-inner">
          <div class="item-title">Google</div>
        </div>
      </a>
    </li>
    <li>
      <a href="http://idangero.us" target="_blank" class="item-link item-content">
        <div class="item-inner">
          <div class="item-title">iDangero.us</div>
        </div>
      </a>
    </li>
  </ul>
</div>

注:自定义函数应在编译模板之前注册。

移除自定义函数:

Template7.unregisterHelper(name)

name - string - 函数名称

全局变量:

Template7.global = { os: 'iOS', browser: 'Chrome', username: 'johndoe', email: 'john@doe.com' };

使用:<p>Hello, {{@global.username}}. Your email is {{@global.email}}</p>

访问数据根节点:

有时候我们在循环的时候需要用到根节点的数据,可以使用{{@root}}来达到目的:

{
    persons: [
        {
            name: 'John',
            hobby: ['Cars', 'Food']
        },
        {
            name: 'Kyle',
            hobby: ['Travel', 'Puzzles']
        },
 
    ],
    showHobby: true
}   

{{#each persons}}
    <h2>{{name}}</h2>
    <h3>Hobby:</h3>
    {{#if @root.showHobby}}
        <ul>
            {{#each hobby}}
                <li>{{this}}</li>
            {{/each}}
        </ul>
    {{/if}}
{{/each}} 

  

部分模板:

创建:Template7.registerPartial(name, template) - register partial

name - string - partial name 模板名称
helper - string - partial template 模板内容

移除:Template7.unregisterPartial(name) - unregister partial

name - string - partial name 模板名称

调用方法:{{> "partialName"}}

原模板:

<ul class="users">
    {{#each users}}
    {{> "user"}}
    {{/each}}
</ul>
<ul class="admins">
    {{#each admins}}
    {{> "user"}}
    {{/each}}
</ul>

注册部分模板:

Template7.registerPartial('user', '<li><h2>{{firstName}} {{lastName}}</h2><p>{{bio}}</p></li>');

应用模板数据:

{
    users: [
        {
            firstName: 'John',
            lastName: 'Doe',
            bio: 'Lorem ipsum dolor'
        },
        {
            firstName: 'Jane',
            lastName: 'Doe',
            bio: 'Donec sodales euismod augue'
        }
    ],
    admins: [
        {
            firstName: 'Mike',
            lastName: 'Doe',
            bio: 'Lorem ipsum dolor'
        },
        {
            firstName: 'Kate',
            lastName: 'Doe',
            bio: 'Donec sodales euismod augue'
        }
    ]
}

输出结果:

<ul class="users">
    <li>
        <h2>John Doe</h2>
        <p>Lorem ipsum dolor</p>
    </li>
    <li>
        <h2>Jane Doe</h2>
        <p>Donec sodales euismod augue</p>
    </li>
</ul>
<ul class="admins">
    <li>
        <h2>Mike Doe</h2>
        <p>Lorem ipsum dolor</p>
    </li>
    <li>
        <h2>Kate Doe</h2>
        <p>Donec sodales euismod augue</p>
    </li>
</ul>

  

递归使用部分模板:

我们甚至可以递归使用部分模板,如嵌套的注释:

// Simple template with just a partial
var template = '{{> "comments"}}'
 
// Register partial
Template7.registerPartial(
    'comments', 
    '<ul>' + 
        '{{#each comments}}' +
            '<li>' +
            '<h2>{{author}}</h2>' +
            '<p>{{text}}</p>' +
            '{{#if comments}}{{> "comments"}}{{/if}}' +
            '</li>' +
        '{{/each}}' +
    '</ul>'
);
 
// Compile template 
var compiledTemplate = Template7.compile(template);
 
// Render template 
var output = compiledTemplate({
    comments: [
        {
            author: 'John Doe',
            text: 'Lorem ipsum dolor',
            comments: [
                {
                    author: 'Mike Doe',
                    text: 'Aliquam erat volutpat'
                },
                {
                    author: 'Kate Doe',
                    text: 'Donec eget fringilla turpis'
                }
            ]
        },
        {
            author: 'Jane Doe',
            text: 'Donec sodales euismod augue'
        }
    ]
})

  

输出结果:

<ul class="comments">
    <li>
        <h2>John Doe</h2>
        <p>Lorem ipsum dolor</p>
        <ul class="comments">
            <li>
                <h2>Mike Doe</h2>
                <p>Aliquam erat volutpat</p>
            </li>
            <li>
                <h2>Kate Doe</h2>
                <p>Donec eget fringilla turpis</p>
            </li>
        </ul>
    </li>
    <li>
        <h2>Jane Doe</h2>
        <p>Donec sodales euismod augue</p>
    </li>
</ul> 

 

原文地址:https://www.cnblogs.com/xsj1989/p/5603685.html