Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you share data across multiple templates?

I sometimes find myself declaring the same data to multiple templates. For example:

Template.auction_page.auctionDurations = function () {
  return [ 30, 60, 120 ];
};

Template.auction_editor.auctionDurations = function () {
  return [ 30, 60, 120 ];
};

I can make it better by using a global:

Template.auction_page.auctionDurations = function () {
  return global.auctionDurations;
};

Template.auction_editor.auctionDurations = function () {
  return global.auctionDurations;
};

But is there any way to get rid of the declarations altogether? In other words, is there any way to share some global data to multiple templates by default?

like image 620
Dave Avatar asked Dec 22 '12 08:12

Dave


People also ask

Can we use multiple templates for a single component?

Note Although it's possible for a component to render multiple templates, we recommend using an if:true|false directive to render nested templates conditionally instead. Create multiple HTML files in the component bundle.

What is ng template?

ng-template is an Angular element that is used for rendering HTML in a template. However, it is not rendered directly on DOM. If you include an ng-template tag to a template, the tag and the content inside it will be replaced by comment upon render.


2 Answers

Found a good solution (with the help of a Helper!).

Your global:

global = _.extend({}, {
  regions: [ "Americas", "Europe", "Asia" ]
}

The helper:

Handlebars.registerHelper("global", function(name) {
    return global[name];
});

Now all your templates can make use of it:

<select>
  {{#each global "regions"}}
  <option>{{this}}</option>
  {{/each}}
</select>
like image 83
Dave Avatar answered Sep 30 '22 03:09

Dave


The use of a helper function is a pretty good general purpose solution. For completeness, you can also do a simple assignment:

Template.auction_page.auctionDurations = Template.auction_editor.auctionDurations;
like image 42
David Wihl Avatar answered Sep 30 '22 04:09

David Wihl