Say I have a helper that looks like this:
Template.profile.helpers({
info: {
Name: 'Bob Dinkleberg',
Age: 45,
Location: 'Earth, Milky Way'
}
});
I want to put this info in a <ul>
. Here is some pseudo-code:
<template name="profile>
<ul>
{{#each}}
<li> {{key}}: {{property}} </li>
{{/each}}
</ul>
</template>
Forgive me if this is trivial, I am new to Meteor and Blaze, and I haven't been able to find a solution online.
If you want to loop through an objects properties and values as you requested, you can do it generic by:
Template.content.onCreated(function() {
this.properties = new ReactiveVar({
Name: 'Bob Dinkleberg',
Age: 45,
Location: 'Earth, Milky Way'
});
});
Template.content.helpers({
keys: function () {
return Object.keys(Template.instance().properties.get());
},
key_value_pair: function() {
return { key: this, value: Template.instance().properties.get()[this] };
}
});
and with this template
<body>
<h1>Property Loop</h1>
<ul>
{{> content}}
</ul>
</body>
<template name="content">
{{#each keys}}
{{> property key_value_pair }}
{{/each}}
</template>
<template name="property">
<li>{{key}}: {{value}}</li>
</template>
I prepared this MeteorPad for you which is a running example:
http://meteorpad.com/pad/24MGwbuMNCcXCC7EW/PropertyLoop
Cheers, Tom
P.S.: It is not necessary to create the object as a ReactiveVar if there a never changes to its values. But by doing it as a ReactiveVar the form is als reactivly updated, when object content will change.
This will be helpful:
http://meteorcapture.com/spacebars/
You want to use {{#with}}
.
<template name="profile">
<ul>
{{#with info}}
<li>{{Name}}</li>
<li>{{Age}}</li>
<li>{{Location}}</li>
{{/with}}
</ul>
</template>
While your helper code is correct:
Template.profile.helpers({
info: {
Name: 'Bob Dinkleberg',
Age: 45,
Location: 'Earth, Milky Way'
}
});
I personally like to make a habit of mapping the name of the helper to a function that returns something.
Template.profile.helpers({
info: function(){
return {
Name: 'Bob Dinkleberg',
Age: 45,
Location: 'Earth, Milky Way'
};
}
});
EDIT
Template.content.helpers({
info: function(){
var obj = {
Name: 'Bob Dinkleberg',
Age: 45,
Location: 'Earth, Milky Way'
};
var arrayOfObjects = [];
// creating an array of objects
for (key in obj){
arrayOfObjects.push({key: key, value: obj[key]});
};
console.log("This is the array of objects: ", arrayOfObjects);
return arrayOfObjects;
},
});
HTML:
{{#each info}}
{{value}}
{{/each}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With