- Building Single:page Web Apps with Meteor
- Fabian Vogelsteller
- 363字
- 2021-08-06 19:29:37
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:
- For the next examples, we will create a file called
examples.html
in ourmy-meteor-blog/client/templates
folder and add the following code snippet:<template name="contextExample"> <p>{{someText}}</p> </template>
- Now that we have our
contextExample
template, we can add it to ourhome
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}}
.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. - 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"' } }; } });
- Now we can add this helper as the data context to our
contextExample
template inclusion helper, as follows:{{> contextExample dataContextHelper}}
- 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}}
- Python從小白到大牛
- Building a RESTful Web Service with Spring
- VSTO開發入門教程
- ANSYS Fluent 二次開發指南
- Python機器學習算法: 原理、實現與案例
- OpenGL Data Visualization Cookbook
- Scratch3.0趣味編程動手玩:比賽訓練營
- 計算機應用基礎教程(Windows 7+Office 2010)
- Lift Application Development Cookbook
- 計算機應用基礎項目化教程
- RocketMQ實戰與原理解析
- 計算機應用技能實訓教程
- 監控的藝術:云原生時代的監控框架
- Visual C++從入門到精通(第2版)
- 透視C#核心技術:系統架構及移動端開發