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

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>.');
      }
    });
主站蜘蛛池模板: 新田县| 吉安县| 常山县| 聂拉木县| 融水| 克拉玛依市| 上犹县| 建湖县| 海城市| 海淀区| 清水县| 华安县| 崇明县| 酉阳| 阜宁县| 五莲县| 蓝田县| 金山区| 乐东| 容城县| 五莲县| 白沙| 鞍山市| 石台县| 南昌县| 浦城县| 大邑县| 伊吾县| 夹江县| 巴彦县| 惠安县| 肇庆市| 邵阳市| 广宗县| 遵化市| 渭源县| 华坪县| 天气| 湟源县| 博罗县| 辉南县|