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> 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM