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

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}}
主站蜘蛛池模板: 榆社县| 神农架林区| 康乐县| 儋州市| 枣强县| 宜兴市| 滨州市| 铜山县| 海盐县| 都兰县| 疏附县| 行唐县| 左云县| 明星| 尖扎县| 舞钢市| 阜南县| 喀喇| 万源市| 宁陵县| 万荣县| 宜阳县| 宜州市| 社会| 广宁县| 蒲城县| 枣阳市| 平乡县| 永丰县| 济阳县| 榆中县| 乌拉特中旗| 山丹县| 巴林左旗| 从江县| 澄城县| 镇安县| 陆良县| 恭城| 迁安市| 古浪县|