Rendering Template in Meteor and Iron Router depending on value in document - meteor

I am trying to render a template depending on a value of a field in a document.
I tried using a switch case in a helper but the return value comes out incorrect.
units_list.html
<template name="unitsList">
{{#each units}}
{{> unitItem}}
{{/each}}
</template>
units_list.js
Template.unitsList.helpers({
units: function() {
return Units.find({}, {sort: {name: 1}});
}
});
unit_item.html
<template name="unitItem">
{{name}}
</template>
unit_item.js
Template.unitItem.helpers({
unitType: function() {
var unitType = this.unitType;
switch(unitType){
case 'first': return "{{pathFor 'unitPageFirst'}}";
case 'second': return "{{pathFor 'unitPageSecond'}}";
}
}
});
I'm either going about this the wrong way or missing something elementary...
I've cut out a lot of code to focus on the problem.
Any ideas on how to get this working, or any suggestions on how to do it better?

You can't return uncompiled Spacebars strings from JS at execution time.
You can either use Router.path to get the path for your routes within your template helper :
Template.unitItem.helpers({
unitType: function() {
var unitType = this.unitType;
switch(unitType){
case 'first':
return Router.path('unitPageFirst', this);
case 'second':
return Router.path('unitPageSecond', this);
}
}
});
Or you can use plain Spacebars by declaring template helpers to check against the unitType.
HTML
<template name="unitItem">
{{#if unitTypeIs 'unitTypeFirst'}}
{{name}}
{{/if}}
{{#if unitTypeIs 'unitTypeSecond'}}
{{name}}
{{/if}}
</template>
JS
Template.unitItem.helpers({
unitTypeIs: function(unitType){
return this.unitType == unitType;
}
});

Have a look at Rendering Templates in the Iron-router guide, specifically the this.render('xyz'); statement
https://github.com/iron-meteor/iron-router/blob/devel/Guide.md#rendering-templates

Related

Meteor: Spacebars each parameter

I'm new to Meteor.js and have run into a problem.
I am passing in a user object to a profile template e.g.:
{
_id: "D8JpXRQskm3grykjg",
username: "foo",
profile: {communities: ["AkGCakz6mSgMb8qyS", "j8aB3i5iscrC4ehkA"]},
}
<template name="profile">
<h1> {{username}}: {{_id}} </h1>
<h3>Communities</h3>
<hr>
{{#each profile.communities}}
{{> communityItem}}
{{/each}}
</template>
The problem is I've already written a communityItem template that I am using elsewhere which accepts the communityName. Is there a way that I can write a helper function, passing in the communityIds list that would return a list of community names? I would like:
...
{{#each getCommunityNames(profile.communities)}}
{{> communityItem}}
{{/each}}
...
I could very well be approaching the problem the wrong way or not writing in a "Spacebars" fashion. Thanks!
sure you can:
Template.myTemplate.helpers({
getCommunityNames: function(commIds) {
var communities = Communities.find({_id: {$in: commIds}}).fetch();
return _.pluck(communities, 'name'); // returns ['Name 1', 'Name 2'];
}
});
Note, the syntax method param not method(param)
{{#each getCommunityNames profile.communities}}
{{>communityItem}}
{{/each}}

'this' context in Meteor event is empty object

Template works fine (in terms of data being displayed), but event doesn't. Particularly odd because I have a different template with almost the identical code in which it works.
<template name="profile_sidebar">
{{#if opened}}
{{> profile_sidebar_contents}}
{{/if}}
</template>
<template name="profile_sidebar_contents">
{{#if dataReady}}
{{#unless equalsCurrentUsername profile.login}}
<span>
<a class="message-user"><i class="ion-chatbox"></i> Message</a>
</span>
{{/unless}}
{{/if}}
</template>
Template.profile_sidebar_contents.events({
'click .message-user': function(e,t){
// this is {}
// t.data is null
Session.set('selectedConversation', this._id);
Router.go('/messages');
}
});
Thank you!
Found a solution!
I wrapped the entire template in a {{#with profile}} ... {{/with}} block and then added the data I needed to be within the profile object returned in the helper. It seems as though the context of the event was empty object because the event target was not within a scope.
Elaborated below
I assumed that the context would default to an object which had as fields all helpers. Ex. I had
Template.profile_sidebar_contents.helpers({
profile: function(){ return something },
id: function() {return somethingelse }
});
and I expected the context of this to be {profile: something, id: somethingelse}
but it seems that this isn't done and the context is empty. I moved it to be
Template.profile_sidebar_contents.helpers({
profile: function(){ return {profile:something, id:somethingelse} }
});
and then set {{#with profile}} ... {{/with}} and had access to the profile helper returned object, by which I could retrieve id by this.id and profile by this.profile

How to deal with the situation that template is rendered but the data is not ready?

In client startup I subscribe to something:
Meteor.publish("Roles", function(){
return Roles.find();
});
Meteor.startup(function() {
if(Meteor.isClient) {
Meteor.subscribe('Roles');
}
});
And roles template:
Template.roles.helper(function() {
allRoles: function() {
return Roles.find().fetch();
}
})
<template name="roles">
<div>
{{#with allRoles}}
<label>{{> role }}</label>
</div>
</template>
The problem is sometime roles template is rendered before the Roles is ready.
How to deal with this situation?
You can do the subscribe on the template and then use the Template.subscriptionReady helper to create a conditional to show a loading panel whilst your subscription is being loaded as follows:
Template.roles.onCreated(function () {
this.subscribe("Roles");
});
Template.roles.helper(function() {
allRoles: function() {
return Roles.find().fetch();
}
})
<template name="roles">
<div>
{{#if Template.subscriptionsReady}}
{{#with allRoles}}
<label>{{> role }}</label>
{{else}}
Loading...
{{/if}}
</div>
</template>
This replaces your other subscription and these subscriptions can be added to each onCreated method for each template to have subscriptions per template.
There are some common ways of dealing with it. You can use a guard or make use of iron router's waitOn function. With a guard you only return data from the helper if you're getting any results:
allRoles: function() {
var roles = Roles.find();
//explicit version
if (roles.count()) return roles
//implicitly works as well here because you're returning null when there are no results
return roles
}
You don't need the fetch() in this case, because #with works with a cursor. If you run into a situation where you need to fetch first because you're returning partial data, check that there are results first and only then return them.
You can also use iron router's waitOn Option if you're using this as part of a route.

Accessing parent context in Meteor templates and template helpers

I'm running into a template context situation that I'm having a hard time finding a way around.
Here's the template in question:
{{#each votes}}
<h3>{{question}}</h3>
<ul>
{{#each participants}}
<li>
<p>{{email}}</p>
<select name="option-select">
{{#each ../options}}
<option value="{{option}}" class="{{is_selected_option}}">{{option}}</option>
{{/each}}
</select>
</li>
{{/each}}
</ul>
</div>
{{/each}}
And here's an example of a vote document:
{
_id: '32093ufsdj90j234',
question: 'What is the best food of all time?'
options: [
'Pizza',
'Tacos',
'Salad',
'Thai'
],
participants: [
{
id: '2f537a74-3ce0-47b3-80fc-97a4189b2c15'
vote: 0
},
{
id: '8bffafa7-8736-4c4b-968e-82900b82c266'
vote: 1
}
]
}
And here's the issue...
When the template drops into the #each for participants, it no longer has access to the vote context, and therefore doesn't have access to the available options for each vote.
I can somewhat get around this by using the ../options handlebars path to jump back into the parent context, but this doesn't affect the context of the template helper, so this in Template.vote.is_selected_option refers to the current participant, not to the current vote or option, and has no way of knowing which option we are currently iterating through.
Any suggestions on how to get around this, without resorting to DOM manipulation and jQuery shenanigans?
This is a templating issue that has come up multiple times for me. We need a formal way of reaching up the template context hierarchy, in templates, template helpers, and template events.
It seems since Spacebars (Meteor's new template engine), you have access to the parent context within {{#each}} blocks using ../.
In Meteor 0.9.1, you can also write a helper and use Template.parentData() in its implementation.
It's not particularly pretty, but I've done something like this:
<template name='forLoop'>
{{#each augmentedParticipants}}
{{> participant }}
{{/each}}
</template>
<template name='participant'>
...
Question: {{this.parent.question}}
...
</template>
// and in the js:
Template.forLoop.helpers({
augmentedParticipants: function() {
var self = this;
return _.map(self.participants,function(p) {
p.parent = self;
return p;
});
}
});
It's similar to the approach that AVGP suggested, but augments the data at the helper level instead of the db level, which I think is a little lighter-weight.
If you get fancy, you could try to write a Handlebars block helper eachWithParent that would abstract this functionality. Meteor's extensions to handlebars are documented here: https://github.com/meteor/meteor/wiki/Handlebars
I don't know the formal way (if there is one), but to solve your issue, I would link the participants with the parent ID like this:
{
_id: "1234",
question: "Whats up?",
...
participants: [
{
_id: "abcd",
parent_id: "1234",
vote: 0
}
]
}
and use this parent_id in helpers, events, etc. to jump back to the parent using findOne.
That is obviously a sub optimal thing to do, but it's the easiest way that comes to my mind as long as there is no way of referencing the parent context.
Maybe there is a way but it is very well hidden in the inner workings of Meteor without mention in the docs, if so: Please update this question if you find one.
It's a long shot, but maybe this could work:
{{#with ../}}
{{#each options}}
{{this}}
{{/each}}
{{/with}}
This should make life easier.
// use #eachWithParent instead of #each and the parent._id will be passed into the context as parent.
Handlebars.registerHelper('eachWithParent', function(context, options) {
var self = this;
var contextWithParent = _.map(context,function(p) {
p.parent = self._id;
return p;
});
var ret = "";
for(var i=0, j=contextWithParent.length; i<j; i++) {
ret = ret + options.fn( contextWithParent[i] );
}
return ret;
});
Go ahead and change
p.parent = self._id;
to whatever you want to access in the parent context.
Fixed it:
// https://github.com/meteor/handlebars.js/blob/master/lib/handlebars/base.js
// use #eachWithParent instead of #each and the parent._id will be passed into the context as parent.
Handlebars.registerHelper('eachWithParent', function(context, options) {
var self = this;
var contextWithParent = _.map(context,function(p) {
p.parent = self._id;
return p;
});
return Handlebars._default_helpers.each(contextWithParent, options);
});
This works :) with no error
Simply register a global template helper:
Template.registerHelper('parentData',
function () {
return Template.parentData(1);
}
);
and use it in your HTML templates as:
{{#each someRecords}}
{{parentData.someValue}}
{{/each}}
======= EDIT
For Meteor 1.2+, you shold use:
UI.registerHelper('parentData', function() {
return Template.parentData(1);
});
I was stuck in a similar way and found that the Template.parentData() approach suggested in other answers currently doesn't work within event handlers (see https://github.com/meteor/meteor/issues/5491). User Lirbank posted this simple workaround:
Pass the data from the outer context to an html element in the inner context, in the same template:
{{#each companies}}
{{#each employees}}
Do something
{{/each}}
{{/each}}
Now the company ID can be accessed from the event handler with something like
$(event.currentTarget).attr('companyId')
"click .selected":function(e){
var parent_id = $(e.currentTarget).parent().attr("uid");
return parent_id
},
<td id="" class="staff_docs" uid="{{_id}}">
{{#each all_req_doc}}
<div class="icheckbox selected "></div>
{{/each}}
</td>
{{#each parent}}
{{#each child}}
<input type="hidden" name="child_id" value="{{_id}}" />
<input type="hidden" name="parent_id" value="{{../_id}}" />
{{/each}}
{{/each}}
The _id is NOT the _did of the thing, it's the id of the parent!

Cannot read property '_liveui' of null

I'm getting client side errors(console.log ones) but my app works(I can add users)
The error is the following:
Uncaught TypeError: Cannot read property '_liveui' of null
The project is in my repo:
https://github.com/thiagofm/statusfyit
What is happening?
Meteor has updated its API a bunch since this question was asked, so the original code no longer runs directly.
Using jQuery.html to insert the results of rendering a template is not the normal approach. It is better to use the handlebars template include functionality.
For example, replace:
$().ready(function(){
hello = Meteor.ui.render(function(){
return Template.hello();
});
$('body').html(hello);
});
With:
<body>
{{> hello}}
</body>
To render different things depending on the state of the application, use the 'Session' object to conditionalize includes. For example:
<template name="foo">
{{#if showNewUserDialog}}
{{> newUserDialog}}
{{else}}
other stuff
{{/if}}
</template>
<template name="newUserDialog">
some stuff
</template>
and
Template.foo.showNewUserDialog = function () {
return Session.get('showNewUserDialog');
};
Template.other.events({
'click #new_user': function () {
Session.set('showNewUserDialog', true);
}
});

Resources