官术网_书友最值得收藏!

Displaying data with template helpers

Each template can have functions, which are called template helpers, and they can be used inside the template and child templates.

In addition to our custom helper functions, there are three callback functions that are called when the template is created, rendered, and destroyed. To display data with template helpers, perform the following steps:

  1. To see the three callback functions in action, let's create a file called home.js and save it to our my-meteor-blog/client/templates/ folder with the following code snippet:
    Template.home.created = function(){
      console.log('Created the home template');
    };
    Template.home.rendered = function(){
      console.log('Rendered the home template');
    };
    
    Template.home.destroyed = function(){
      console.log('Destroyed the home template');
    };

    If we now open the console of our browser, we will see the first two callbacks are being fired. The last one will only fire if we dynamically remove the template.

  2. To display data in the home template, we will create a helper function that will return a simple string as follows:
    Template.home.helpers({
      exampleHelper: function(){
        return 'This text came from a helper with some <strong>HTML</strong>.';
      }
    });
  3. Now if we go to our home.html file, add the {{exampleHelper}} helper after the {{markdown}} block helper, and save the file, we will see the string appearing in our browser, but we will notice that the HTML is escaped.
  4. To make Meteor render the HTML correctly, we can simply replace the double curly braces with triple curly braces, as shown in the following line of code, and Blaze won't let the HTML escape:
    {{{exampleHelper}}}

    Note

    Note that in most of our templates helper, we shouldn't use triple stache {{{...}}} as this opens the door for XSS and other attacks. Only use it if the HTML returned is safe to be rendered.

  5. Additionally, we can return unescaped HTML using double curly braces, but we need to return the string passed through the SpaceBars.SafeString function, as shown in the following example:
    Template.home.helpers({
      exampleHelper: function(){
        return new Spacebars.SafeString('This text came from a helper with some <strong>HTML</strong>.');
      }
    });
主站蜘蛛池模板: 化隆| 安丘市| 周口市| 天祝| 凉山| 江华| 临泽县| 修文县| 天峨县| 永胜县| 云安县| 苍溪县| 苍南县| 静海县| 墨竹工卡县| 体育| 丰宁| 峨眉山市| 梅河口市| 湟中县| 德兴市| 文山县| 浑源县| 宁陵县| 鸡泽县| 宜章县| 屯留县| 姚安县| 洪泽县| 栾川县| 靖西县| 华阴市| 龙井市| 咸宁市| 大方县| 宜君县| 德令哈市| 陆良县| 财经| 门源| 香河县|