`

移动端安卓和IOS开发框架Framework7教程-Template7 示例

阅读更多

{{#each}}...{{else}}...{{/each}}

{{#each}} is a block expression, that iterates through items of passed Array or through properties of passed Object.

The following additional variables are available inside of this helper:

  • @index - index number of the item. For arrays only

  • @first - equal to true for the first item in array. For arrays only

  • @last - equal to true for the last item in array. For arrays only

  • @key - name of current object property. For objects only

Iterate through Array items

  1. <!DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <meta charset="utf-8">
  5.         <title>Template7 实例教程
  6.         </title>
  7.     </head>
  8.     <body>
  9.         <div class="views">
  10.             <div class="view view-main">
  11.                 <div class="pages">
  12.                     <script id="homeTemplate" type="text/template7">
  13.                         <div data-page="home" class="page">
  14.                             <div class="page-content">
  15.                                 <div class="content-block">
  16.                                     <p>Here are the list of people i know:</p>
  17.                                     <ul>
  18.                                       {{#each people}}
  19.                                       <li>{{firstName}} {{lastName}}</li>
  20.                                       {{/each}}    
  21.                                     </ul>          
  22.                                 </div>
  23.                             </div>
  24.                         </div>    
  25.                     </script>
  26.                 </div>
  27.             </div>
  28.         </div>
  29.         <script type="text/javascript" src="//ku.shouce.ren/libs/fk7/1.4.2/js/framework7.min.js">
  30.         </script>
  31.         <script>// 声明Dom7
  32.             var $$ = Dom7;
  33.             // 初始化 App
  34.             var myApp = new Framework7({
  35.                 precompileTemplates: true
  36.                 });
  37.             var mainView = myApp.addView('.view-main');
  38.             // Now we may render our compiled template by passing required context
  39.             var context = {
  40.                   people : [
  41.                     {
  42.                       firstName: 'John',
  43.                       lastName: 'Doe'
  44.                     },
  45.                     {
  46.                       firstName: 'Mark',
  47.                       lastName: 'Johnson'
  48.                     },
  49.                   ]
  50.                 }    ;
  51.             mainView.router.load({
  52.                 template: Template7.templates.homeTemplate,
  53.                 context: context
  54.             })
  55.         </script>
  56.     </body>
  57. </html>
复制

实例预览

  1. <p>Here are the list of people i know:</p>
  2. <ul>
  3.     {{#each people}}
  4.     <li>{{@index}}. {{this}}
  5.     </li>
  6.     {{/each}}    
  7. </ul>
  8. <script>
  9. var context = {
  10. people : ['John Doe', 'Mark Johnson']
  11. }
  12. </script>
复制

实例预览

Iterate through Object properties

  1. <p>Car properties:</p>
  2. <ul>
  3.     {{#each props}}
  4.     <li>{{@key}}: {{this}}
  5.     </li>
  6.     {{/each}}
  7. </ul>
  8. <script>
  9.     var context = {
  10.         props: {
  11.             power: '150 hp',
  12.             speed: '200 km/h',
  13.         }
  14.     };
  15. </script>
复制

实例预览

{{else}} expression

  1. <p>Car properties:</p>
  2. <ul>
  3.     {{#each props}}
  4.     <li>{{@key}}: {{this}}</li>
  5.     {{else}}
  6.     <li>No properties</li>
  7.     {{/each}}
  8. </ul> 
  9. <script>
  10.     var context = {
  11.         props: {
  12.             power: '150 hp',
  13.             speed: '200 km/h',
  14.         }
  15.     };
  16. </script>
复制

实例预览

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

{{#if}} helper renders content if passed context is not "false" (or "undefined" or "null" or "" or "0") , otherwise it renders inverse content that optionally could be passed to {{else}} expression inside of helper:

  1. <a href="#" {{#if active}}class="active"{{/if}}>{{title}}</a>
  2. <script>
  3.     var context ={
  4.         active: true,
  5.         title: 'Link',
  6.     };
  7. </script>
复制

实例预览

{{else}} expression

  1. <p>Hello, my name is {{name}}.</p>
  2. {{#if hobby}}
  3. <p>I have hobby</p>
  4. {{else}}
  5. <p>I don't have hobby</p>
  6. {{/if}}  
  7. <script>
  8.     var context ={
  9.         name: 'John Doe',
  10.         hobby: false
  11.     };
  12. </script>
复制

 实例预览

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

{{#unless}} helper renders content if passed context is "false" (or "undefined" or "null" or "" or "0") , otherwise it renders inverse content that optionally could be passed to {{else}} expression inside of helper:

  1. <a href="#" {{#unless active}}class="active"{{/unless}}>{{title}}</a>
  2. <ul>
  3.     {{#each props}}
  4.     <li>{{@key}}: {{this}}
  5.     </li>
  6.     {{/each}}
  7. </ul>
  8. <script>
  9.     var context={
  10.         active: true,
  11.         title: 'Link',
  12.     };
  13. </script>
复制

实例预览

{{else}} expression

  1. <p>Hello, my name is {{name}}.</p>
  2. {{#unless hobby}}
  3. <p>I have hobby</p>
  4. {{else}}
  5. <p>I don't have hobby</p>
  6. {{/unless}}  
  7. <ul>
  8.     {{#each props}}
  9.     <li>{{@key}}: {{this}}</li>
  10.     {{/each}}
  11. </ul>
  12. <script>
  13.     var context={
  14.         name: 'John Doe',
  15.         hobby: false
  16.     };
  17. </script>
复制

实例预览

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

{{#with}} helper changes rendering context to the passed context:

  1. {{#with props}}
  2. <p>Car has {{power}} power and {{speed}} maximum speed</p>
  3. {{/with}}
  4. <script>
  5.     var context={
  6.         props: {
  7.             power: '150 hp',
  8.             speed: '200 km/h',
  9.         }
  10.     };
  11. </script>
复制

实例预览

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

If you pass a block expression with helper name that is in the expression context, then it will work like {{#each}} helper for this context if it is an Array, and will work like {{#with}} helper if it is an Object:

  1. <ul>
  2.     {{#people}}
  3.     <li>{{name}} - {{age}} years old</li>
  4.     {{/people}}
  5. </ul>
  6. <script>
  7.     var context={
  8.         people: [
  9.             {
  10.                 name: 'John Doe',
  11.                 age: 18
  12.             }
  13.             ,
  14.             {
  15.                 name: 'Mark Johnson',
  16.                 age: 21
  17.             }
  18.         ]  
  19.     };
  20. </script>
复制

实例预览

  1. {{#props}}
  2. <p>Car has {{power}} power and {{speed}} maximum speed</p>
  3. {{/props}}
  4. <script>
  5.     var context={
  6.         props: {
  7.             power: '150 hp',
  8.             speed: '200 km/h',
  9.         }
  10.     };
  11. </script>
复制

实例预览

{{join delimiter=""}}

This plain helper will join Array items to single string with passed delimiter

  1. <h3>"{{title}}" TV Show</h3>
  2. <p>Was released in year {{year}}</p>
  3. <p>Genres: {{join genres delimiter=", "}}</p>
  4. <script>
  5.     var context={
  6.         title: 'Friends',
  7.         year: 2001,
  8.         genres: ['comedy', 'drama']
  9.     };
  10. </script>
复制

实例预览

{{escape}}

This plain helper returns escaped HTML string. It escapes only the following characters: < > " &

  1. <h1>{{title}}</h1>
  2. <p>{{escape body}}</p>
  3. <script>
  4.     var context={
  5.         title: 'Paragraphs',
  6.         body: 'We need to use <p> tags to add paragraphs in HTML',
  7.     };
  8. </script>
复制

实例预览

{{js "expression"}}

This inline helper allows to execute some simple JavaScript directly in template to modify/check context on the fly or for some JS calculations

  1. <h3>{{title}}</h3>
  2. <p>Price: ${{js "this.price * 1.2"}}</p>
  3. <p>{{js "this.inStock ? 'In Stock' : 'Not in stock'"}}</p>
  4. <script>
  5.     var context={
  6.         title: 'iPhone 6 Plus',
  7.         price: 1000,
  8.         inStock: true
  9.     };
  10. </script>
复制

实例预览

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

Block helper for easier compares of context variables. It renders content if JavaScript expression is not "false" (or "undefined" or "null" or "" or "0") , otherwise it renders inverse content that optionally could be passed to {{else}} expression inside of helper

  1. <h3>{{title}}</h3>
  2. <p>Price: ${{price}</p>
  3. <p>{{#js_compare "this.color === 'white' && this.memory > 16"}}Not in stock{{else}}In stock{{/js_compare}}</p>
  4. <script>
  5.     var context={
  6.         title: 'iPhone 6 Plus',
  7.         price: 1000,
  8.         color: 'white',
  9.         memory: 32
  10.     };
  11. </script>
复制

实例预览

Using Custom Helpers

Template7 allows to register custom helpers with the following method:

Template7.registerHelper(name, helper)

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

Helper function could accepts as many arguments as required, arguments could be context, strings and hash data.

Let's look how to register helper on example of simple {{#if}} helper:

  1. Template7.registerHelper('if', function (condition, options) {
  2.   // "this" in function context is equal to the expression execution context
  3.   // "condition" argument contains passed context/condition
  4.   /*
  5.     @options contains object with the wollowing properties and methods:
  6.     "hash" - contains passed hash object with parameters
  7.     "fn" - method to pass helper block content further to compilier
  8.     "inverse" - method to pass helper block inverse ({{else}}) content further to compilier
  9.     "data" - contains additional expression data, like @index for arrays or @key for object
  10.   */
  11.  
  12.   // First we need to check is the passed context is function
  13.   if (typeof condition === 'function') condition = condition.call(this);
  14.  
  15.   // If context condition
  16.   if (condition) {
  17.     // We need to pass block content further to compilier with the same context and the same data:
  18.     options.fn(this, options.data);
  19.   }
  20.   else {
  21.     // We need to pass block inverse ({{else}}) content further to compilier with the same context and the same data:
  22.     options.inverse(this, options.data);
  23.   }
  24. });
复制

Or on example of plain {{join}} helper:

  1. Template7.registerHelper('join', function (arr, options) {
  2.   // First we need to check is the passed arr argument is function
  3.   if (typeof arr === 'function') arr = arr.call(this);
  4.  
  5.   /* 
  6.     Passed delimiter is in the options.hash object:
  7.     console.log(options.hash) -> {delimiter: ', '}
  8.   */
  9.  
  10.   // And return joined array
  11.   return arr.join(options.hash.delimiter);
  12. });
复制

Or we can create helper to create Framework7's list-block link to work with this syntax:

  1. {{link url title target="_blank"}}
复制
  1. Template7.registerHelper('link', function (url, title, options){
  2.   var ret = '<li>' +
  3.               '<a href="' + url + '" class="item-content item-link" target="' + options.hash.target + '">' +
  4.                 '<div class="item-inner">' +
  5.                   '<div class="item-title">' + title + '</div>' +
  6.                 '</div>' +
  7.               '</a>' +
  8.             '</li>';
  9.   return ret;
  10. });
复制
  1. <div class="list-block">
  2.   <ul>
  3.     {{#each links}}
  4.     {{link url title target="_blank"}}
  5.     {{/each}}    
  6.   </ul></div>
复制
  1. {
  2.   links: [
  3.     {
  4.       url: 'http://google.com',
  5.       title: 'Google'
  6.     },
  7.     {
  8.       url: 'http://idangero.us',
  9.       title: 'iDangero.us'
  10.     },
  11.   ]
  12. }
复制

输出

  1. <div class="list-block">
  2.   <ul>
  3.     <li>
  4.       <a href="http://google.com" target="_blank" class="item-link item-content">
  5.         <div class="item-inner">
  6.           <div class="item-title">Google</div>
  7.         </div>
  8.       </a>
  9.     </li>
  10.     <li>
  11.       <a href="http://idangero.us" target="_blank" class="item-link item-content">
  12.         <div class="item-inner">
  13.           <div class="item-title">iDangero.us</div>
  14.         </div>
  15.       </a>
  16.     </li>
  17.   </ul>
  18. </div>
复制

Note, that all custom helpers should be registered before you compile templates with these helpers!

Remove Custom Helpers

Template7 allows to remove custom helpers with the following method:

Template7.unregisterHelper(name)

  • name - string - helper name

Global Context

Template7 also supports global context which is accessible from any context.

We can specify it in Template7.global property:

  1. Template7.global = {
  2.     os: 'iOS',
  3.     browser: 'Chrome',
  4.     username: 'johndoe',
  5.     email: 'john@doe.com'
  6. };
复制

To access it in templates we need to use {{@global}} variable:

  1. <p>Hello, {{@global.username}}. Your email is {{@global.email}}</p>
复制

Access To Root Context

Sometimes we may need to access to initially passed root context in our templates. For this case we need to use {{@root}} variable. This is especially helpful when we are deep in context:

  1. {
  2.     persons: [
  3.         {
  4.             name: 'John',
  5.             hobby: ['Cars', 'Food']
  6.         },
  7.         {
  8.             name: 'Kyle',
  9.             hobby: ['Travel', 'Puzzles']
  10.         },
  11.  
  12.     ],
  13.     showHobby: true
  14. }
复制
  1. {{#each persons}}
  2.     <h2>{{name}}</h2>
  3.     <h3>Hobby:</h3>
  4.     {{#if @root.showHobby}}
  5.         <ul>
  6.             {{#each hobby}}
  7.                 <li>{{this}}</li>
  8.             {{/each}}
  9.         </ul>
  10.     {{/if}}
  11. {{/each}}
复制

Partials

Template7 allows to reuse template using through partials. Partials are normal usual Template7 templates that may be called by other templates.

We can register and unregister partials using the following methods:

Template7.registerPartial(name, template) - register partial

  • name - string - partial name
  • helper - string - partial template

Template7.unregisterPartial(name) - unregister partial

  • name - string - partial name

Then we can use our partials using special helper {{> "partialName"}}

Template:

  1. <ul class="users">
  2.     {{#each users}}
  3.     {{> "user"}}
  4.     {{/each}}
  5. </ul>
  6. <ul class="admins">
  7.     {{#each admins}}
  8.     {{> "user"}}
  9.     {{/each}}
  10. </ul>
复制

Register partial:

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

Apply to the template this context:

  1. {
  2.     users: [
  3.         {
  4.             firstName: 'John',
  5.             lastName: 'Doe',
  6.             bio: 'Lorem ipsum dolor'
  7.         },
  8.         {
  9.             firstName: 'Jane',
  10.             lastName: 'Doe',
  11.             bio: 'Donec sodales euismod augue'
  12.         }
  13.     ],
  14.     admins: [
  15.         {
  16.             firstName: 'Mike',
  17.             lastName: 'Doe',
  18.             bio: 'Lorem ipsum dolor'
  19.         },
  20.         {
  21.             firstName: 'Kate',
  22.             lastName: 'Doe',
  23.             bio: 'Donec sodales euismod augue'
  24.         }
  25.     ]
  26. }
复制

And we will get the following output:

  1. <ul class="users">
  2.     <li>
  3.         <h2>John Doe</h2>
  4.         <p>Lorem ipsum dolor</p>
  5.     </li>
  6.     <li>
  7.         <h2>Jane Doe</h2>
  8.         <p>Donec sodales euismod augue</p>
  9.     </li>
  10. </ul>
  11. <ul class="admins">
  12.     <li>
  13.         <h2>Mike Doe</h2>
  14.         <p>Lorem ipsum dolor</p>
  15.     </li>
  16.     <li>
  17.         <h2>Kate Doe</h2>
  18.         <p>Donec sodales euismod augue</p>
  19.     </li>
  20. </ul>
复制

Recursive Partials

We can even use partials to make recursive templates, like nested comments:

  1. // Simple template with just a partial
  2. var template = '{{> "comments"}}'
  3.  
  4. // Register partial
  5. Template7.registerPartial(
  6.     'comments', 
  7.     '<ul>' + 
  8.         '{{#each comments}}' +
  9.             '<li>' +
  10.             '<h2>{{author}}</h2>' +
  11.             '<p>{{text}}</p>' +
  12.             '{{#if comments}}{{> "comments"}}{{/if}}' +
  13.             '</li>' +
  14.         '{{/each}}' +
  15.     '</ul>'
  16. );
  17.  
  18. // Compile template 
  19. var compiledTemplate = Template7.compile(template);
  20.  
  21. // Render template 
  22. var output = compiledTemplate({
  23.     comments: [
  24.         {
  25.             author: 'John Doe',
  26.             text: 'Lorem ipsum dolor',
  27.             comments: [
  28.                 {
  29.                     author: 'Mike Doe',
  30.                     text: 'Aliquam erat volutpat'
  31.                 },
  32.                 {
  33.                     author: 'Kate Doe',
  34.                     text: 'Donec eget fringilla turpis'
  35.                 }
  36.             ]
  37.         },
  38.         {
  39.             author: 'Jane Doe',
  40.             text: 'Donec sodales euismod augue'
  41.         }
  42.     ]
  43. })
复制

And the output will be:

  1. <ul class="comments">
  2.     <li>
  3.         <h2>John Doe</h2>
  4.         <p>Lorem ipsum dolor</p>
  5.         <ul class="comments">
  6.             <li>
  7.                 <h2>Mike Doe</h2>
  8.                 <p>Aliquam erat volutpat</p>
  9.             </li>
  10.             <li>
  11.                 <h2>Kate Doe</h2>
  12.                 <p>Donec eget fringilla turpis</p>
  13.             </li>
  14.         </ul>
  15.     </li>
  16.     <li>
  17.         <h2>Jane Doe</h2>
  18.         <p>Donec sodales euismod augue</p>
  19.     </li>
  20. </ul>
复制

Performance Tips

Template7 is fast and you can make it even faster in your apps. The slowest part (but still very fast in T7) in compilation/rendering process is the compilation from string to pure JS function when you do Template7.compile(). So don't compile the same templates multiple times, one time will be enough:

  1. // Begin of your app
  2.  
  3. // Compile templates once on app load/init
  4. var searchTemplate = $('script#search-template').html();
  5. var compiledSearchTemplate = Template7.compile(searchTemplate);
  6.  
  7. var listTemplate = $('script#list-template').html();
  8. var compiledListTemplate = Template7.compile(listTemplate);
  9.  
  10. // That is all, now and further just execute compiled templates with required context
  11. // Just execute compiled search template with required content:
  12. var html = compiledSearchTemplate({/*...some data...*/});
  13.  
  14. // Do something with html...
0
0
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics