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

Setting the data context for a template

Now that we've seen how we can display data using a helper, let's see how we can set the whole data context of a template:

  1. For the next examples, we will create a file called examples.html in our my-meteor-blog/client/templates folder and add the following code snippet:
    <template name="contextExample">
      <p>{{someText}}</p>
    </template>
  2. Now that we have our contextExample template, we can add it to our home template by passing some data as follows:
    {{> contextExample someText="I was set in the parent template's helper, as an argument."}}

    This will show the text in the contextExample template because we were displaying it using {{someText}}.

    Tip

    Remember that filenames don't really matter as Meteor is collecting and concatenating them anyway; however, the template name matters since we use this to reference templates.

    Setting the context in HTML is not very dynamic, as it is hardcoded. To be able to dynamically change the context, it is better to set it using a template helper function.

  3. To do this, we must first add the helper to our home templates helpers, which returns the data context, as follows:
    Template.home.helpers({
      // other helpers ...
      dataContextHelper: function(){
        return {
          someText: 'This text was set using a helper of the parent template.',
          someNested: {
            text: 'That comes from "someNested.text"'
          }
        };
      }
    });
  4. Now we can add this helper as the data context to our contextExample template inclusion helper, as follows:
    {{> contextExample dataContextHelper}}
  5. Also, to show the nested data object we return, we can use Blaze dot syntax in the contextExample template by adding the following line of code to the template:
    <p>{{someNested.text}}</p>

This will now display both the someText and the someNested.text, which was returned by our helper functions.

Using the {{#with}} block helper

Another way of setting the data context is by using the {{#with}} block helper. The following code snippet has the same result as the former inclusion helper that utilizes the helper function:

{{#with dataContextHelper}}
  {{> contextExample}}
{{/with}}

We would even get the same results in the browser when we don't use a subtemplate and just add the content of the contextExample template inside the {{#with}} block helper, as follows:

{{#with dataContextHelper}}
  <p>{{someText}}</p>
  <p>{{someNested.text}}</p>
{{/with}}
主站蜘蛛池模板: 锦州市| 长泰县| 德昌县| 磐石市| 长乐市| 大悟县| 横峰县| 电白县| 泸溪县| 惠安县| 岱山县| 肇庆市| 佳木斯市| 社旗县| 依兰县| 磴口县| 孟村| 岐山县| 江北区| 嘉祥县| 溧水县| 藁城市| 永胜县| 许昌市| 古蔺县| 灯塔市| 缙云县| 饶平县| 石河子市| 镇赉县| 偃师市| 富源县| 元江| 新沂市| 长子县| 林西县| 五常市| 托克托县| 阳信县| 沙雅县| 云龙县|