Hanlebars Each Helper Context - each

I'm trying to use a handlebars each iterator in the following chunk of template code:
<table>
<tr><th></th><th>Today</th><th>This Month<br>(To Date)</th><th>Last Month</th></tr>
{{#each Activities}}
{{examineObject this}} - first -
<tr><td>{{examineObject this}}</td>
<td>{{Today}}</td>
<td>{{ThisMonth}}</td>
<td>{{LastMonth}}</td></tr>
{{examineObject this}} - third -
{{/each}}
<tr class='total'><td>Net Change</td>
<td>{{Totals.Today}}</td>
<td>{{Totals.ThisMonth}}</td>
<td>{{Totals.LastMonth}}</td></tr>
</table>
examineObject is a handlebars helper I have written to simply call JSON.stringify() on the variable. I'm doing this to evaluate the context. The helper is simply:
examineObject: function(object){
return JSON.stringify(object);
}
When I compile and render the template above, something very odd happens. The context of this at both the first and third examineObject call is the individual activity selected by the each iterator. However, the context of this in the second examineObject call (surrounded by html tags) is the context of the entire template - NOT the context of the individual activity selected by the each iterator. Can anyone explain why this would be?

Don't use jQuery's .find() to get your handlebars template because it will be scraping a rendered DOM, which may be different from your written file contents.
Instead, try loading your template file asynchronously
Update:
Or if you have a multitude of templates and don't want to run numerous async requests, you may be interested in precompiling the handlebars templates as demonstrated in "Handling handlebars.js like a pro".

Related

#each with partials and dynamic pages with handlebars/express

I'm trying to do a foreach with partials into expressjs project, but I don't get
main.hbs
{{#each pages}}
{{>this}}
{{/each}}
app.js
app.get('/',(req,res)=>{
let pages = ['test1','teste2']
res.render('index',{user:req.user,pages:pages})
})
Then show me this message
Error: The partial this could not be found
The Handlebars documentation states that dynamic partials require parentheses around the expression that evaluates to the partial name. So one would think that {{> (this) }} would be sufficient.
However, in my experiments with this, I could not get this to work. Without digging deeply into the source, I assume there is something special about how this is parsed in this context. Therefore, to get it to work, I had to use as to give me an aliased reference to each page name. My template became:
{{#each pages as |page|}}
{{> (page) ..}}
{{/each}}
Note: The .. is there to set the parent object of pages as the context of the partial.
I have created a fiddle for reference.
Thank you my friend !!! Now it works !!!

handlebarsjs get the value of the selected option dynamically

I've been working with pug/jade a little bit and now I'm trying to build the same project using handlebars.
I have this iteration that renders a few options:
<select id="myselect" name="myselect">
{{#each categories}}
<option value="{{id}}">{{title}}</option>
{{/each}}
</select>
A bit further down the code I need to render some items dynamically based on the selected item from myselect.
Any idea how I can grab it dynamically? Basically the same way like onchange() works in plain javascript.
When you use any kind of tempting engine (handlebars, jade, ejs, etc). You cannot bind data after the response sent to the client. You have to write some client side javascript code to achieve that.
As an alternative you can use handlebarjs on client side. Follow this link
But this may need to be used carefully, since you are using the same template engine on your server side.

Adding additional content blocks in KeystoneJS with handlebars

I'm using handlebars with KeystoneJS and am trying to extend the main import in the default template. At the moment it only includes the {{{body}}} tag imported through the view plus the partials that I'm using.
Is there any way to add a couple of other imports (i.e. intro content, page title, additional scripts). In the jade version on the demo site it just imports it as a content block. Is this a limitation of handlebars?
You can do this with handlebars just fine using partials.
Put your partial in the folder indicated below:
Then in your layout ('default.hbs' in this case) reference the partial like you would normally in handlebars.
<div id="header">
{{> navigation this}}
</div>
The '>' means insert partial.
In this case 'navigation' is the
partial name in the partials folder.
'this' is the data context. Its what you want to do with the 'locals.data' object passed into handlebars by keystone. Using 'this' will pass the whole lot through whereas doing something like 'locals.data.navigation' would pass the navigation object through to the partial making it directly accessible in the partial (good for DRY).
Hope that helps. The partials specific documentiation for handlebars is here if you are interested in looking into a few more things you can do with scope etc http://handlebarsjs.com/partials.html

Meteor Iron-Router Layout Rendering

We have implemented a layout where the main content resides in dynamic sidebars. We defined following layoutTemplate:
<template name="layout">
{{> content}}
{{> leftbar}}
{{> rightbar}}
<nav class="navigation">
{{#if currentUser}}
{{> navigation_logged_in}}
{{else}}
{{> navigation_logged_out}}
{{/if}}
</nav>
</template>
We include e.g. the rightbar template in the layout template.
<template name="rightbar">
<aside class="rightbar">
<button id="closeRightBar" class="close-cross"></button>
{{yield 'rightbar'}}
</aside>
</template>
The rightbar template includes the rightbar yield where we yield the specific content into.
We have implemented following RouteController:
UserShowRouter = RouteController.extend({
before: function() {
var username = this.params.username;
if(App.subs.user) {
App.subs.user.stop();
}
App.subs.user = Meteor.subscribe('user', username);
},
waitOn: function () {
return Meteor.subscribe('user');
},
data: function() {
return Meteor.users.findOne({'profile.username': this.params.username});
},
action: function() {
this.render('profile', {to: 'rightbar'});
}
});
What we wanted to achieve is that for example the profile template is yielded into the rightbar yield and get's updated and re-rendered as the data changes.
The problem is now that the sidebars are dynamically animated, shown and hidden. Now every time the profile template gets re-rendered also the layout template gets re-rendered. Why is that? We thought one of the purposes of yield regions is that the whole site doesn`t need to be re-renderd. Now when the layout gets re-rendered the whole css of the animations are set back to the original values.
We now have tried several different approaches, but none of them seems to be a good and clean solution. Is there a way to keep the layout template from being re-rendered and just keep the yield region and template up-dated? Any suggestions or alternatives would be highly appreciated.
As I understand it, the behavior in which re-rendering of your templates "bubbles up" and causes re-rendering of their parent templates is not particular to iron-router or the way your code is implemented, but is inherent in Spark. Iron-router's {{yield}} pattern does not alter this behavior, as far as I can tell from its documentation.
The good news is that Spark is set to be replaced imminently with a newer, more fine-grained rendering engine, currently codenamed "Spacebars," which should alleviate the concern.
Here is a preview of the new rendering system:
https://github.com/meteor/meteor/wiki/New-Template-Engine-Preview
This talk from a week ago is also excellent at describing the benefits coming through the new rendering engine (while fairly long, an overview is given in the first 5 minutes):
https://www.youtube.com/watch?v=aPf0LMQHIqk
As for your options today, you can:
a) Use the {{#constant}} and {{#isolate}} parameters to try to limit re-rendering.
b) Work from a development branch as described in the link above:
You can play with the current work-in-progress version of the code using the template-engine-preview-4 release tag (run your app with meteor --release template-engine-preview-4), or by checking out the shark branch (it's an internal codename).
c) Best of all if the timeframe of your project allows is to allow the re-rendering to continue until Meteor 1.0 hits and "Spacebars" resides on the main branch - it sounds like this is 1-3 months away.
I think that the reason your layout template gets rerendered is because the data hook you implemented uses a reactive data source. If the current user object changes, the router probably decides to rerender the whole page because there is no simple way to decide which parts exactly depend on your reactive data.
If I'm right, a simple solution to your problem is to create a user helper that will fetch the necessary data only where they're actually needed, e.g.
Template.profile.user = function () {
return Meteor.users.findOne({/*...*/});
}
Then you can use it in your profile template along with the with helper (sic!), i.e.
{{#with user}}
...
{{/with}}
to prevent multiple calls to the Template.profile.user function.
Also, if I were you, I would use the data hook only for data which is required by templates in my layout.

Expression Engine - Pass loop variable into embeded template

have some trouble with Expression Engine variable passing in templates.
There is some piece of code:
// query:
{exp:channel:entries
channel="static"
}
// repeating field in a loop
{content_matrix}
<div>
{text_cell}
</div>
{image}
{/content_matrix}
//
{/exp:channel:entries}
I want to move content_matrix field with big inner HTML (example is shorter) sctructure into separate embed template for reusage in other templates.
Tried to build such embed but it doesnt work:
{embed="incl/content_matrix" matrix="{content_matrix}"}
And body of smaller template:
{embed:matrix}
<div>
{text_cell}
</div>
{image}
{/embed:matrix}
In this way it works if you passing single element, like ID, but not for mupltiple element.
Maybe it needs to pass entire entry.
How it can be done?
Thanks.
Have you considered using the Stash add-on?
I imagine you can stash the matrix content dividing between different parts of your html with some kind of separator, then in the embedded template wrap a search/replace for the separators with the proper html around the grabbed stash.
It might be less of a pain to write a quick, custom plugin, though.
Embed variables pass parsed output, not tags. So in your example:
{embed="incl/content_matrix" matrix="{content_matrix}"}
What you're actually passing in the matrix parameter is the full HTML table output of the data in that particular entry (since Matrix fields output a table when used as a single tag).
I think what you actually want to use to prevent repeating yourself is a Snippet. So just make a snippet containing:
{content_matrix}
<div>
{text_cell}
</div>
{image}
{/content_matrix}
And save it as, say, matrix_loop. Then include it inside your Channel Entries loop like so:
{matrix_loop}

Resources