Meteor- pass data to nested templates - templates

Meteor newbie here.
I have a template for a home page. The home pages has several "day"s in it, which each have "task"s. I want to display the appropriate task in the day that it belongs to, but I don't know how to do this.
I also only want to retrieve the relevant tasks with one database query if possible (ie all tasks within two weeks).
I found a couple other questions possibly related to this including this and this but I can't discern any useful related info.
I have a collection for tasks, and as part of the home page I retrieve a two week span of tasks. Then I sort them into day buckets.
buckets = [[...], [...], [...], ... ] # array of arrays of task objects
Now I don't know what to do. In the home template, I think I can do
Template.home.helpers(
tasks: ()->
#return buckets, defined above
)
(home.coffee)
<template name="home">
{{#each tasks}}
{{> day}}
{{/each}}
</template>
(home.html)
to iterate over the day buckets, but how do I access the task objects from each day template?
<template name="day">
{{#each ???}}
{{> task}}
{{/each}}
</template>
<template name="task">
{{name}}
</template>
How can I access the data from the current iteration of the each loop from the parent template? Am I structuring this incorrectly? Should I just make separate db calls for every day?

This should do the trick:
<template name="day">
{{#each this}}
{{> task}}
{{/each}}
</template>
Edit: this is the incorrect original answer.
Let task have fields called name, important and dueToday. Then you may write:
<template name="day">
{{name}}
</template>
Or, if you insist:
<template name="day">
{{this.name}}
</template>
Also:
Template.day.isItUrgent = function() {
return this.data.important && this.data.dueToday;
};

Related

Meteor each loop within template

So I'm looking for some understanding on how templates and such work.
I've movie.html file with a template named movies in it, with a movie.js helper that returns a collection.
Movies Template
<template name="movies">
<li>{{title}}</li>
</template>
JS Helpers
Template.body.helpers({
movie: function () {
return Movies.find({});
}
});
Now I've another template that does a bunch of other things but one of them is to iterate over this list and display it.
List Template
<template name="list">
<ul>
{{#each movie}}
{{> movies}}
{{/each}}
</ul>
</template>
In this situation the list doesn't popular with the data.
However, if I move the contents of the list template outside of a template and just on the main.html it works great!
This is how I used to use it but I've started to use Houston Admin Package which uses Iron:Router so I've moved the main (and only) page to a template for routing purposes, which breaks my looping list.
I'm sure I'm missing something minor but I can't figure it out.
You are using the {{#each movie}} helper on the list Template so change the Template.helper to the list template
Template.list.helpers({
movie: function () {
return Movies.find({});
}
});
We are you calling this <template name="list"> on the body tag? you have something like this.
<body>
{{> list}}
</body>
Or you have something like this.
<template name="layout">
{{> yield}} <!-- since you are mentioning iron:route package -->
</template>
Or you have a route to that list template? localhost:3000/lists
Router.route('/movie-lists', function () {
this.render('lists')
});
On whatever of this 3 cases, you should point the helper into the template where you are calling it (in this case list template)

Iron router dynamic template rendering

In my meteor project, I have added iron:layout, iron:dynamic-template along with iron:router.
My question is, how can you prevent the dynamic template from rendering if there is no data available in the Session? The reason is, the dynamic template is currently being rendered with all html content within it except for data context. This is the problem when the user initially arrives onto the page.
I have a list of names on 'postlist' template. These are 'usernames' of the person who created the post. When a user clicks on the name, the template 'viewpost' is rendered with the relevant data passed...that is fine. But as stated earlier, there is no data context when the user first arrives onto the page. So the see all the content except for the dynamic content.
The following is my current code, with help received from my previous post. Meteor: Render template inside a template
HTML:
<template name="postlist">
<div class="container">
<div class="col-sm-3">
{{#each post}}
<li>{{fullname}}</li>
{{/each}}
</div>
</div>
{{> Template.dynamic template='viewpost' data=currentPost}}
</template>
Click event to capture post _id / helper file:
Template.postlist.helpers({
currentPost: function(){
return Posts.findOne(Session.get('currentPost'));
}
});
Template.postlist.events({
'click li': function(e){
e.preventDefault();
Session.set("currentPost", this._id);
}
});
This is one alternative hack method but understand is not good practice. This is what I am effectively wanting to achieve so you get an idea. But I would like non-hack suggestions for this issue. Thank you.
html:
<template name="viewpost">
{{#if hasData}}
<div class="container">
Post creator is : {{username}} - Info: {{body_text}}
</div>
{{/if}}
</template>
js:
Template.viewpost.helpers({
"hasData":function(){
return Session.get("currentPost");
}
});

How can I have Meteor add an attribute to many template links?

I'm trying to add an attribute to many external links. The below code worked prior to Blaze, which only runs Template.rendered once now (but the below code doesn't run as desired one time even).
So what is an alternative way to add an attribute to many links once the page has been rendered or what is the correct way to do this with Meteor now? BTW, I researched quite a few things, including this example app from the author, which if it has the answer, I didn't see it.
Template.layout.rendered = function () {
console.log('CALLED'); // runs
$(document).ready(function () {
console.log('NOW THIS'); // runs
$('a.external').each(function () {
console.log('NOT CALLED'); // doesn't run
$(this).attr('target', '_blank');
});
});
};
There are several ways to deal with this problem, none of them is perfect. It's worth noting that this issue has been raised and most likely it will be solved via a custom event as proposed here.
For now, the simplest way to do this is to move each element you need to adjust to a separate template. So instead of:
<template name="layout">
{{#each links}}
<a class="external" ...>
{{/each}}
</template>
You will have:
<template name="layout">
{{#each links}}
{{> layout_externalLink}}
{{/each}}
</template>
<template name="layout_externalLink">
<a class="external" ...>
</template>

Ember.Component (block form): more than one outlet {{yield}}

I see that ember has a very nice mechanism for wrapping content in a component using the {{yield}} mechanism documented here.
So, to use the example in the documentation, I can have a blog-post component template defined like so:
<script type="text/x-handlebars" id="components/blog-post">
<h1>{{title}}</h1>
<div class="body">{{yield}}</div>
</script>
I can then embed blog-post into any other template using the form:
{{#blog-post title=title}}
<p class="author">by {{author}}</p>
{{body}}
{{/blog-post}}
My question is, can I specify two different {{yield}} outlets in the components template?
Something like this is possible via Named Outlets in Ember.Route#renderTemplate like so:
Handlebars:
<div class="toolbar">{{outlet toolbar}}</div>
<div class="sidebar">{{outlet sidebar}}</div>
JavaScript:
App.PostsRoute = Ember.Route.extend({
renderTemplate: function() {
this.render({ outlet: 'sidebar' });
}
});
I'm not sure I can take this path for a component which will not know what route's template would be rendering it.
EDIT 1:
For the sake of clarity, I'm trying to implement the Android Swipe for Action Pattern as an Ember component.
So, I'd like users of this component to be able to specify two different templates:
A template for the normal list item, and
A template for the actions that are revealed when a swipe on (1) is detected.
I want to make this into a component, because quite a lot of javascript goes into handling the touch(start/move/end) events, while still managing smooth touch based scrolling of the list. Users would supply the two templates and this component would manage handling of touch events and necessary animations.
I've managed to get the component working in the block form, where the block's contents are treated like (1). The second template (2) is specified through a parameter (actionPartial below) which is the name of a partial template for the actions:
Component Handlebars Template: sfa-item.handlebars
<div {{bind-attr class=":sfa-item-actions shouldRevealActions:show" }}>
{{partial actionPartial}}
</div>
<div {{bind-attr class=":sfa-item-details isDragging:dragging shouldRevealActions:moveout"}}>
{{yield}}
</div>
Calling Handlebars Template:
{{#each response in controller}}
<div class="list-group-item sf-mr-item">
{{#sfa-item actionPartial="mr-item-action"}}
<h5>{{response.name}}</h5>
{{/sfa-item}}
</div>
{{/each}}
Where the mr-item-action handlebars is defined like so:
mr-item-action.handlebars:
<div class="sf-mr-item-action">
<button class="btn btn-lg btn-primary" {{action 'sfaClickedAction'}}>Edit</button>
<button class="btn btn-lg btn-primary">Delete</button>
</div>
Problem is, actions from the user supplied partial, sfaClickedAction above, are not bubbled up from the component. A fact which is mentioned in the docs in para 4.
So, now I do not know how a user could capture actions that he defined in the supplied actions template. A component cannot catch those actions because it doesn't know about them either.
EDIT 2
I sprung a follow up question here
This blog post describes the most elegant solution for Ember 1.10+: https://coderwall.com/p/qkk2zq/components-with-structured-markup-in-ember-js-v1-10
In your component you pass yield names into {{yield}}s:
<header>
{{yield "header"}}
</header>
<div class="body">
{{yield "body"}}
</div>
<footer>
{{yield "footer"}}
</footer>
When you invoke your component, you accept the yield name as a block param... and use an esleif chain!
{{#my-comp as |section|}}
{{#if (eq section "header")}}
My header
{{else if (eq section "body")}}
My body
{{else if (eq section "footer")}}
My footer
{{/if}}
{{/my-comp}}
PS eq is a subexpression helper from the must-have ember-truth-helpers addon.
PPS Relevant RFC: proposal, discussion.
Since it is not possible to have two {{yield}} helpers within one component (how would the component know where one {{yield}}'s markup stops and the next one begins?) you may be able to approach this problem from a different direction.
Consider the pattern of nested components. Browsers do this already with great success. Take, for example, the <ul> and <li> components. A <ul> wants to take many bits of markup and render each one like a member of a list. In order to accomplish this, it forces you to separate your itemized markup into <li> tags. There are many other examples of this. <table>, <tbody>, <tr>, <td> is another good case.
I think you may have stumbled upon a case where you can implement this pattern. For example:
{{#sfa-item}}
{{#first-thing}}
... some markup
{{/first-thing}}
{{#second-thing}}
... some other markup
{{/second-thing}}
{{/sfa-item}}
Obviously first-thing and second-thing are terrible names for your specialized components that represent the things you'd want to wrap with your first and second templates. You get the idea.
Do be careful since the nested components won't have access to properties within the outer component. You'll have to bind values with both outer and inner components if they are needed in both.

Context inside templates with Iron-Router

I'm having trouble understanding exactly what is available as my context in a template invoked by Meteor with Iron-Router – and how these things inherit.
Here are all the potential sources for "stuff I can refer to inside double curly braces" that I can think of:
Built-in helpers
Handlebars.registerHelper(...)
Template.myTemplate.myVar/myHelper = ...
Template.myTemplate.helpers({ ... })
data: { ... } inside route (Router.map)
Something to do with #each?
Something to do with #with?
Have I forgotten anything? Are there any global variables?
I guess I'm a bit confused about what the standard way is of giving the template a context in the first place. Also about what happens inside control structures such as #each and #with.
A clarification would be great!
IronRouter renders your template with the result of RouteController.data as the current data context.
<template name="viewPost">
<div>
<h1>{{title}}</h1>
<p>{{content}}</p>
</div>
</template>
var PostsController=RouteController.extend({
template:"viewPost",
waitOn:function(){
return Meteor.subscribe("postsById",this.params._id);
},
data:function(){
return Posts.findOne(this.params._id);
}
});
this.route("viewPost",{
path:"/posts/:_id",
controller:PostsController
});
In this example, IronRouter will render the "viewPost" template with the post having this.params._id as data context.
What is the standard way of giving a template a context in the first place ?
There is 2 ways :
{{#with myContext}}
{{> myTemplate}}
{{/with}}
{{> myTemplate myContext}}
As you can see, the #with control structure sets the current data context.
The #each structure iterates over a Cursor (or an Array) and sets the current data context to the current fetched document (or the current cell).
<template name="postsList">
{{#each posts}}
<h1>{{title}}</h1>
{{/each}}
</template>
Template.postsList.helpers({
posts:function(){
// cursor
return Posts.find();
// array
return [{title:"Title 1"},{title:"Title 2"},{title:"Title 3"}];
}
});
UPDATE : Could you possibly add a note about inheritance ? For instance, if I have nested #each blocks, do variables cascade ?
I came up with this example :
<template name="parent">
<ul>
{{#each parentContexts}}
{{> child}}
{{/each}}
</ul>
</template>
<template name="child">
<li>
<ul>
{{#each childContexts}}
{{> content}}
<p>../this.parentProperty = {{../this.parentProperty}}</p>
{{/each}}
</ul>
</li>
</template>
<template name="content">
<li>
<p>this.childProperty = {{this.childProperty}}</p>
<p>this.parentProperty = {{this.parentProperty}}</p>
</li>
</template>
Template.parent.helpers({
parentContexts:function(){
return [{
parentProperty:"parent 1"
},{
parentProperty:"parent 2"
}];
}
});
Template.child.helpers({
childContexts:function(){
return [{
childProperty:"child 1"
},{
childProperty:"child 2"
}];
}
});
If you run this example, you'll notice that you can't access the parentProperty in "content" because the default #each helper OVERRIDES the parent data context with the new context provided.
You can access the parentProperty in the nested #each block using this syntax : ../this.parentProperty, which is reminiscent of the UNIX parent directory access syntax.
However you cannot use this syntax in the "content" template, because it is agnostic of the nested each structures it was called from : you can only use the ../../parent syntax in a template where the actual nesting happens.
If we want to access the parentPropery in the content template, we must augment the current data context with the parent context.
To do so, we can register a new #eachWithParent helper like this :
Handlebars.registerHelper("eachWithParent",function(context,options){
var parentContext=this;
var contents="";
_.each(context,function(item){
var augmentedContext=_.extend(item,parentContext);
contents+=options.fn(augmentedContext);
});
return contents;
});
Now if you replace the nested #each with this new helper, you will have access to parentProperty in "content".