Is it possible to get the length of json object inside the handlebars template using the property .length .
{{json.length}}
If not is it possible to find the length based on the list of keys and then using the .length such as
{{json.keys.length}}
Sample JSON structure
{1232134235423:[Name,Destination,Desc],
2134213214321:[Name],
2342354356634:[Name,Desc]
}
Edit 1:I know this can be achieved by using a custom helper but this length has to be used inside custom if helper. So something like array.length would be useful
If I understand your edit right the problem is not to use another helper but to call it within another helper's call.
Thus, you could use a second helper nested in your custom if-helper call:
{{#customIf (objectLength json)}}
do some stuff...
{{/customIf}}
According to this answer "Getting JavaScript object key list" you can use Object.keys(json) to get all your object's keys.
The new helper objectLength could look like that:
Handlebars.registerHelper("len", function(json) {
return Object.keys(json).length;
});
You can check length of object in handlebars template like this in your template. So HTML will render only when the object have one or more child element.
{
people: [
"abc",
"Alan Johnson",
"Charles Jolley",
],
}
{{#if people.length}}
<p>{{ people}} </p>
<ul class="people_list">
{{#each people}}
<li>{{this}}</li>
{{/each}}
</ul>
{{/if}}
Related
I am using a helper inside another helper. I am trying to pass a value ‘post_id’, that i am getting dynamically from ‘show_post’ helper.I want to pass it and then use it inside the query that is returning a set of result back to helper. for some reason , app is crashing. Can someone guide me through this.
{{#each show_post}}
{{posttext}}
{{postedBy}}
{{#each show_comment({{post_id}}) }}
//<--- i am passing the value to helper like this.
<span> <p>{{postedBy}}: <h5>{{commenttext}}</h5>{{createdAt}}</p></span>
{{/each}}
{{/each}}
Template.display_block.helpers({
show_post(){
return PostComment.find({parent: 0},{sort: {createdAt: -1}});
}
});
Template.display_block.helpers({
show_comment(e){
var t1 = e;
var now = PostComment.find({post_id:{$regex:new RegExp(’^’ + t1)}});
return now;
}
});
The first helper generates a array(Mongo Db result).I want to use this array’s elements(that are dynamic) in next helper. So i want to use a variable that can hold the value of array element of first helper and then pass it to next helper. In second helper, i want to pass this variable and use this variable to sort a result in Mongo query. I am new to this so i am unable to understand how this instance
Firstly you don't need to wrap helper arguments in double curly braces or parens.
{{#each show_comment post_id}}
Will do what you need.
You're also making life a bit more complicated for yourself than necessary. You can use the current data context through this in your code. Also unclear why you're using a regex unless you're concatenating something to the post _id.
This allows you to simplify down to:
html:
{{#each show_post}}
{{posttext}}
{{postedBy}}
{{#each show_comment}}
<span><p>{{postedBy}}: <h5>{{commenttext}}</h5>{{createdAt}}</p></span>
{{/each}}
{{/each}}
js:
Template.display_block.helpers({
show_comment(){
return PostComment.find({post_id: this._id);
}
});
Let's say I have the following Blaze template helper that fetches some objects from a collection:
PackageInCart: function() {
PackageIds = Carts.findOne({SessionId: SessionID}).Packages;
var PackageObjects = Packages.find({ _id: { $in : PackageIds } } ).fetch();
return PackageObjects;
},
The PackageObjects variable contains objects that have a 'priceperday' property with a certain price value. In the Blaze template, I can easily print this value using:
{{#each PackageInCart}}
<div class="price">{{priceperday}}</div>
{{/each}}
However, what if I want to modify the 'priceperday' value from the Helper function before it gets printed in the template? What would be the correct way to do this?
One solution that came to mind was to make a for loop that iterates over the objects and does something like Object.defineProperty() to change the priceperday property into the new value.
I want to know if there's an easier or quicker way using Blaze methods to modify the object property that gets printed with the curly braces.
If you want to do this using blaze you could do this using another helper.
weeklyPrice: function(priceperday){
return priceperday * 7;
}
Which would be called like this
{{#each PackageInCart}}
<div class="price">{{weeklyPrice priceperday}}</div>
{{/each}}
More info about spacebars helper arguments in the docs
everybody :) For example I have something like this:
{{> someCoolHelper
someParam1='someVal1'
someParam2='someVal2'
someParam3='SomeVal3'
someParam4=someAnotherHelper 'value param to this helper'
}}
So I have a function, that computes some value depending on parameter that can be passed in it. So how can I do this?
as you may read in a forum thread at meteor forum this is not possible by now in spacebars.
We began with a new package for chaining methods and arguments but its not released yet. What you could do is to use the WITH element like
Instead something like:
{{> someCoolHelper
someParam1='someVal1'
someParam2='someVal2'
someParam3='SomeVal3'
someParam4=someAnotherHelper 'value param to this helper'
}}
can be managed by:
{{#with someAnotherHelper 'value param to this helper' }}
{{> someCoolHelper
someParam1='someVal1'
someParam2='someVal2'
someParam3='SomeVal3'
someParam4=this
}}
{{/with}}
I don't like it, but sometimes necessary
Tom
P.S.: Or drop Spacebars and use React - you won't have such limitations there.
The placeholder solution until template sub expressions are available in Spacebars is to create an helper returning the adequate value in JS :
HTML
{{> myTemplate param1="A" param2=param2}}
JS
function someOtherHelper(param){
console.log(param);
}
Template.registerHelper("someOtherHelper", someOtherHelper);
Template.myTemplate.helpers({
param2: function(){
return someOtherHelper("B");
}
});
You can pass the output of a helper to another helper using parentheses. Pretty sure this is what you're after:
http://blazejs.org/guide/spacebars.html#Calling-helpers-with-arguments
You can also pass the output of a helper to a template inclusion or other helper. To do so, use parentheses to show precedence:
{{> Todos_item (todoArgs todo)}}
Here the todo is passed as argument to the todoArgs helper, then the output is passed into the Todos_item template.
Something I did in a recent project uses this functionality to allow conditional rendering of CSS classes to a component (stripped down for brevity):
# global helper to provide ternary operator
Template.registerHelper('ternary', (condition, resultTrue, resultFalse) => {
return condition ? resultTrue : resultFalse
})
# in my-template.js:
Template.My_template.helpers({
isComplete(score) {
return score === 1
}
})
# in my-template.html:
{{> some_component class=(ternary (isComplete this.score) "green" "red")}}
So I am trying use a helper as an argument of another helper in Spacebars. In the example below, 'getResultInfo' is a helper that gets data specific to the arguments passed, and 'formatResult' is a helper that formats its result and the results of other helpers.
<template name="example">
{{#each collectionResults}}
Label: {{formatResult getResultInfo this._id 'text'}}
{{/each}}
</template>
The issue I'm having is that Spacebars thinks that the arguments for 'getResultInfo' are the just second and third arguments for 'formatResult'. I'd really like to keep the helper's functions separate (ie. not having to format the result at the end of the 'getResultInfo' and every other helper that I have). Is there any alternate syntax or method of doing what I'm trying to achieve?
I think that you cannot chain two helpers with parameters on the second one like you did. Subsequent parameters will still be interpreted as parameters from the first helper.
I see two ways for solving this problem:
1) you could get rid of the parameters and use the data context provided by each.
each bind the data context to this so in getResultInfo you could just use this._id directly. But you have to remember that you need this data context each time you use this helper. And this pose a problem with the 'text' parameter which does not depend from the data context.
2) you could create a function corresponding to your getResultInfo helper and use it directly in the formatResult helper like this:
getResultHelper = function(id, text) {
//do what you want
};
//bind the function to your getResultInfo (example with a global helper)
Template.registerHelper('getResultInfo', getResultHelper);
//use the function in your template helper
Template.example.helpers({
formatResult: function(format) {
return getResultHelper(this._id, format);
}
});
//and finally your template
<template name="example">
{{#each collectionResults}}
Label: {{formatResult 'text'}}
{{/each}}
</template>
FYI, this is now possible in Meteor 1.2, via Spacebars sub expressions in Blaze.
<template name="example">
{{#each collectionResults}}
Label: {{formatResult (getResultInfo this._id 'text')}}
{{/each}}
</template>
For my app I'm trying to set an operation on each item of a collection of Widgets. A widget Item contains an url (api rest), and a period. The goal is to loop through a widget collection and do something like this :
//Loop through collection
Meteor.setInterval(function(){
Meteor.call('getData', <Collection>.url,function(e,r){
if(e){
console.error(e);
}else{
//Display the data into the template
}
});
},<Collection>.period);
In the template I'd like to do something like this :
{{#each widgets}}
{{widgetItem}}
{{/each}}
I'd like to know what is the best way to do this ? I heard about Dynamics Templates with Telescope App but I don't know if it would be useful in my case.
The {{#each}} Spacebars magic changes the data context of the elements inside it.
Basically, assuming you have the following or a similar data structure for your widget:
{
templateName : 'coolWidget1',
templateData : { ... }
}
You could write something along the lines of:
{{#each Widgets}}
{{> Template.dynamic template=templateName data=templateData}}
{{/each}}
Where template= and data= are the object parameters you pass to Template.dynamic (it will produce { template : templateName, data : templateData}).
Then you can just pass templateName and templateData thanks to the {{#each}} changing the data context (Spacebars understand that you mean "the templateName and templateData of the current item of the loop).
So that was for the HTML. If you want to share the returned value from the call with the template, search for questions about Session or ReactiveVar, there's already a lot of stuff asked about it.