Meteor - display collection with conditions - javascript

I have a user based Meteor application with a collection representing groups.
A group is something like this:
{ name: groupname, members: [memberuseridlist], owner: owneruserid}
I have a template for these groups that looks like this:
{{#each groups}}
<li>{{name}}
-
<button class="join">+</button>
<button class="leave">-</button>
<button class="delete">x</button>
</li>
{{/each}}
But I'd like to ensure that only the relevant buttons are displayed e.g.:
{{#each groups}}
<li>{{name}}
-
{{#unless ismember}}<button class="join">+</button>{{/unless}}
{{#if ismember}}<button class="leave">-</button>{{/if}}
{{#if isowner}}<button class="delete">x</button>{{/if}}
</li>
{{/each}}
I have a set of template helper methods but I don't understand how to pass the actual group into the function, so that I can evaluate ismember and isowner for each group.

The context within {{#each groups}} is a group document. So within your helpers you can use this to mean a group. Try something like this:
Template.myTemplate.helpers({
ismember: function() {
return _.contains(this.memberuseridlist, Meteor.userId());
},
isowner: function() {
return this.owner === Meteor.userId();
}
});
If you wish to make these helpers more portable between your templates, see my article on models.

Related

If equals validate in handlebar template inside each loop

I have a php array like this one
bookings[] = {"arrived","cancelled","departed"};
When display this array in handlebars template i want to check IF equal condition.
In the following example when value is equals to cancelled i want to display some text.
{{#each bookings}}
{{#if this.value cancelled}}
cancelled
{{/if}}
{{/each}}
This code is not working. What is alternative IF equals condition for handlebars to execute in loop.
Now my code is working,
bookings = ["arrived", "cancelled", "departed"];
Handlebar function:
Handlebars.registerHelper('check_status', function(val1, val2) {
return val1 === val2;
});
Handlebar template:
{{#if (check_status this 'cancelled')}}
If I'm not mistaken you can't do an actual conditional in handlebars, you can only do if true/false which means that the **value** in {{#if **value**}} need to either be true or false
So what you will want to do is in the area of code where this.value is defined create a function like this
valueIsCancelled = function(value) {
return value === 'cancelled';
}
In your template you will do:
{{#each bookings}}
{{#if this.valueIsCancelled this.value}}
cancelled
{{/if}}
{{/each}}
or another option is to define another variable where value is defined that would be a boolean
var isCancelled = value === 'cancelled';
and your template would look like this
{{#each bookings}}
{{#if this.isCancelled}}
cancelled
{{/if}}
{{/each}}

Emberjs model rendering

I just started learning emberjs and wanted to display a list of data from the models. My app.js:
var h= [{
name: "Hi",
},
{
name: "Hello",
}
];
App.ListsRoute = Ember.Route.extend({
model: function(){
return h;
}
});
my corresponding lists handlebar:
<div id="list">
<ul>
{{#each}}
<li>
{{ name }}</li>
{{/each}}
</ul>
</div>
I get the error as:
Error: Assertion Failed: The value that #each loops over must be an Array. You passed (generated lists controller)
What is that I can do to display those?
#each wants to iterate over a list. Since you didn't give it an argument, it defaults to trying to iterate over your ListsController. Unfortunately, since you didn't define it, the controller was auto-generated based on the plain Ember.Controller. Thus, the error.
Two ways to fix this:
1) Make ListsController into an ArrayController
App.ListsController = Ember.ArrayController.extend({});
2) Tell #each to target your model instead of controller.
<div id="list">
<ul>
{{#each model}}
<li>{{ name }}</li>
{{/each}}
</ul>
</div>

meteor: render a template in a specific context

I have two templates
<body>
{{>tmpl1}}
{{>tmpl2}}
....
</body>
in the tmpl1 I have a list of items, which can be clicked. When one is click, tmpl2 shown the details. How can this be achieved ?
So, just to make the idea clearer, here is how I get the list of items
Template.tmpl1.items = function () {
return Items.find({}).fetch();
};
tmpl1 displays them as follows
<template name="tmpl1">
{{#each items}}
{{title}}
{{/each}}
....
</template>
So tmpl2 template might look like this
<template name="tmpl1">
<h1>{{title}}</h1>
<p>{{content}}</p>
</template>
Any suggestions how to link the selected item in tmpl1 with tmpl2 ?
First, put your templates in a container so that you can manipulate the context. Also, put the details template in a #with context:
<template name="box">
{{> list}}
{{#with item}}
{{> details}}
{{/with}}
</template>
Now, add the event handlers for the box template. Assuming your entries in the list looks like this:
<div class="listItem" data-id="{{_id}}">{{title}}</div>
Write the handler:
Template.box.events({
'click .listItem': function(e, t) {
t.data.itemId = $(e.target).data('id');
t.data.itemDep.changed();
}
});
Finally, create the data helper and dependency for the selected item:
Template.box.created = function() {
this.data.itemDep = new Deps.Dependency();
};
Template.box.item = function() {
this.itemDep.depend();
return Items.findOne(this.itemId);
};

Dynamically loading templates in Meteor.js

I would like the ability to load templates dynamically without explicitly specifying the template.
As an example:
<template name="foo">
</template>
where 'foo' is the template, I would like the ability to load it dynamically by calling some method:
Meteor.render(Meteor.loadTemplate('foo'));
Is this possible?
Here's how to dynamically render templates, as of Meteor 0.9.4 - 1.0. All other answers were obsolete at the time of this writing.
Let's say you're editing a bunch of records, or creating a new one, and want to render either the update template, or the new template, based on some Session variables.
There are two ways to do this:
1) This is the officially recommended method for Meteor 0.9.4 or newer - it uses Template.dynamic:
<template name="records">
{{> Template.dynamic template=whichOne}}
</template>
<template name="recordUpdate">
...
</template>
<template name="recordNew">
...
</template>
Template.records.helpers({
whichOne: function () {
return Session.get('edit') ? 'recordUpdate' : 'recordNew'
// note that we return a string - per http://docs.meteor.com/#template_dynamic
}
});
2) This works in various Meteor versions, but isn't recommended officially because it's unclear that the template is chosen dynamically:
<template name="records">
{{> whichOne}}
</template>
{{! Note how "whichOne" is indistinguishable from a constant template name... }}
{{ ...like "recordUpdate" or "recordNew" below. }}
<template name="recordUpdate">
...
</template>
<template name="recordNew">
...
</template>
Template.records.helpers({
whichOne: function () {
return Session.get('edit') ? Template.recordUpdate : Template.recordNew
// note that we return a Template object, not a string
}
});
To pass a data context to the template, use:
{{> Template.dynamic template=whichOne data=myData}}
Meteor 0.9.x New API
Dan Dascalescu pointed out Meteor now has built-in dynamic templates! This is nice because you do not need to include the extra code as seen in previous versions.
{{> Template.dynamic template=template [data=data] }}
For Meteor 0.8.x Legacy
Dynamic Template Without Data: Boris Kotov's updated Blaze (0.8.0) answer is on the right track (taken from the latest docs), but it doesn't work as-is for me. I got the following to work:
{{> dynamicTemplate name=myDynName}}
<template name="dynamicTemplate">
{{#with chooseTemplate name}}
{{> template}}
{{/with}}
</template>
Template.dynamicTemplate.chooseTemplate = function (name) {
return { template: Template[name] };
};
I hope there is a simpler solution, but I needed to wrap the Template in a JSON as shown. Maybe this will help someone else to move forward.
Dynamic Template With Data: If you have and want data to be dynamic, be sure to make a helper method that can react. Be sure to do a Session.set() somewhere to see the effect.
// Inside "myContainingTemplate"
{{> dynamicTemplateWithData name=myDynName data=myDataHelper}}
<template name="dynamicTemplateWithData">
{{#with chooseTemplate name}}
{{#with ../data}}
{{> ..}}
{{/with}}
{{/with}}
</template>
Template.dynamicTemplateWithData.chooseTemplate = function (name) {
return Template[name];
};
Template.myContainingTemplate.helpers({
myDataHelper: function () {
Session.get('myReactiveKey');
}
});
You have found Meteor.render but what you are missing is the template loading.
In the docs it mentions that you can call Template.foo() to return the HTML for a template.
http://docs.meteor.com/#template_call
Putting that together you access the template foo or any other using bracket access so:
var templateName = "foo";
var fragment = Meteor.render( function() {
return Template[ templateName ](); // this calls the template and returns the HTML.
});
Then fragment is your Reactive fragment, so that your template can continue to receive live updates. Your fragment now needs placing in the web page (I use jQuery, so this example does as well):
$("#htmlnode").html( fragment );
$("#htmlnode") is just a node in your DOM where you want the template rendered. And you now have the rendered content in your web page.
I'm just doing it like this, no jQuery required:
EDITED
Template.mainContent.showContentFromRouter = function() {
return Template[Meteor.Router.page()]();
};
In this case I'm using the Meteor Router, and return whatever template that I choose to (from the Router), but you could just do this:
Template.mainContent.showDynamicContent = function() {
return Template['someTemplateYouveDefined']();
};
Update for blaze:
https://github.com/meteor/meteor/wiki/Using-Blaze#templatefoo-is-not-a-function-and-does-not-return-a-string
Dynamically render a template with a given data context
Old:
{{dynamicTemplate name="templateName" data=dataContext}}
Template.foo.dynamicTemplate = function (opts) {
return Template[opts.name](opts.data);
};
New: (Notably, in Blaze, keyword arguments to inclusion or block helpers are bundled into a single object which becomes the new data context)
{{> dynamicTemplate name="templateName" data=dataContext}}
<template name="dynamicTemplate">
{{#with chooseTemplate name}}
{{#with ../data}} {{! original 'data' argument to DynamicTemplate}}
{{> ..}} {{! return value from chooseTemplate(name) }}
{{/with}}
{{/with}}
</template>
Template.dynamicTemplate.chooseTemplate = function (name) {
return Template[name];
}
By the way, I don't really played with it, but this is what I took from the new blaze docs. So I think it should be the way to do it ;)
From https://github.com/meteor/meteor/wiki/Using-Blaze
{{> post}}
Template.foo.helpers({
post: function () {
return Template[this.postName];
}
});
Template inclusions now search the namespace of helpers and data for template objects, so it's easy to programmatically choose which template to use. This is a powerful feature, and will allow patterns like assigning one template as a helper of another so that it can be overridden.
Meteor 0.8.x Legacy
Using Joc's answer as a guide,
I've achieved similar using http://docs.meteor.com/#template_call, but using a helper instead, as suggested by the docs:
When called inside a template helper, the body of Meteor.render, or other settings where reactive HTML is being generated, the resulting HTML is annotated so that it renders as reactive DOM elements
My client.js looks a bit like this:
Template.myPageTemplate.helpers({
dynamicTemplate: function() {
// conditional logic can be added here to determine which template to render
return Template.myDynamicTemplate();
}
});
and my html looks like this:
<template name="myPageTemplate">
<h1>My Template</h1>
{{{dynamicTemplate}}}
</template>
<template name="myDynamicTemplate">
<h1>My Dynamic Template</h1>
</template>
Based on hillmark's answer, this is the easiest it could get:
Template.main.template = function() {
if (some_condition) {
return Template.A();
} else {
return Template.B();
}
};
With the corresponding .html
<body>
{{> main}}
</body>
<template name="main">
{{{template}}}
</template>
<template name="A">
<h1>Template A</h1>
</template>
<template name="B">
<h1>Template B</h1>
</template>
Edit
Doesn't work in Meteor 0.8.0
for me the easiest way was to just create a function get_dynamic_template, so something like:
var a= get_dynamic_template(template_name,data);
which returns what can be rendered as a normal variable {{a}}
The code for this function is quite simple:
var get_dynamic_template = function(template_name,data)
{
return function(){
return new Handlebars.SafeString(
UI.toHTML(
Template[template_name].extend({data: function () { return data; }}))
);
};
}
This would handl dynamic templates both with and without data:
(requires Blaze/ Meteor 0.8)
{{> dynamicTemplate name=templateName}}
<template name="dynamicTemplate">
{{#with chooseTemplate name }}
{{#if ../data}}
{{#with ../data }}
{{> .. }}
{{/with}}
{{else}}
{{> this}}
{{/if}}
{{/with}}
<template name="dynamicTemplate">
template javascript:
Template.dynamicTemplate.chooseTemplate = function (name) {
return Template[name];
};

Best way to store "temp" data on an ember button

I have an Ember.Button which should remove an element from an array. The button label is simply an X (for now).
I'd like to know the best way to store data for use by the button. If this was plain jquery I might use data-username. But what's the best way to do this?
update
Use case for this question would be something like this:
{{#each App.recentUsersArray}}
<li>
{{#view App.RecentNameBtn contentBinding="this"}} {{content}} {{/view}}
{{#view App.RecentNameDeleteBtn}}X{{/view}}
</li>
{{/each}}
In the second view, I need a way to know which username the delete action should apply to.
Use the {{action}} helper, which passes the context as argument, see http://jsfiddle.net/zVd9g/. Note: in the upcoming Ember.js version the action helper only passes one argument so you would have to adapt your sources accordingly.
If you want to use your existing views, you could do a contentBinding="this" on the App.RecentNameDeleteBtn as you already did on the App.RecentNameBtn.
Handlebars:
<script type="text/x-handlebars" >
{{#each App.arrayController}}
<button {{action "showTweets" target="App.arrayController" }} >{{this}}</button>
<button {{action "removeItem" target="App.arrayController" }}>x</button>
<br/>
{{/each}}
</script>​
JavaScript:
App = Ember.Application.create({});
App.arrayController = Ember.ArrayProxy.create({
content: [1, 2, 3, 4, 5, 6],
removeItem: function(view, evt, item) {
console.log('remove user %#'.fmt(item));
this.removeObject(item);
},
showTweets: function(view, evt, item) {
console.log('show tweets of user %#'.fmt(item));
}
});​

Categories