Meteor Block Helper that acts like a template - meteor

Here's what I want, a custom block helper that can act like a template, monitoring for it's own events etc. The html would look like this:
{{#expandable}}
{{#if expanded}}
Content!!!
<div id="toggle-area"></div>
{{else}}
<div id="toggle-area"></div>
{{/if}}
{{/expandable}}
And here's some javascript I have put together. This would work if I just declared the above as a template, but I want it to apply to whatever input is given to that expandable block helper.
Template.expandableView.created = function() {
this.data._isExpanded = false;
this.data._isExpandedDep = new Deps.Dependency();
}
Template.expandableView.events({
'click .toggle-area': function(e, t) {
t.data._isExpanded = !t.data._isExpanded;
t.data._isExpandedDep.changed();
}
});
Template.expandableView.expanded = function() {
this._isExpandedDep.depend();
return this._isExpanded;
};
I know I can declare block helpers with syntax like this:
Handlebars.registerHelper('expandable', function() {
var contents = options.fn(this);
// boring block helper that unconditionally returns the content
return contents;
});
But that wouldn't have the template behavior.
Thanks in advance! This might not be really possible with the current Meteor implementation.
Update
The implementation given by HubertOG is super cool, but the expanded helper isn't accessible from within the content below:
<template name="expandableView">
{{expanded}} <!-- this works correctly -->
{{content}}
</template>
<!-- in an appropriate 'home' template -->
{{#expandable}}
{{expanded}} <!-- this doesn't work correctly. Expanded is undefined. -->
<button class="toggle-thing">Toggle</button>
{{#if expanded}}
Content is showing!
{{else}}
Nope....
{{/if}}
{{/expandable}}
In the actual block helper, expanded is undefined, since the real thing is a level up in the context. I tried things like {{../expanded}} and {{this.expanded}}, but to no avail.
Strangely, the event handler is correctly wired up.... it fires when I click that button, but the expanded helper is simply never called from within the content, so even console.log() calls are never fired.

Meteor's new Blaze template engine solves this problem quite nicely.
Here's an excerpt from the Blaze docs showing how they can be used.
Definition:
<template name="ifEven">
{{#if isEven value}}
{{> UI.contentBlock}}
{{else}}
{{> UI.elseBlock}}
{{/if}}
</template>
Template.ifEven.isEven = function (value) {
return (value % 2) === 0;
}
Usage:
{{#ifEven value=2}}
2 is even
{{else}}
2 is odd
{{/ifEven}}

You can achieve this by making a helper that returns a template, and passing the helper options as a data to that template.
First, make your helper template:
<template name="helperTemplate">
<div class="this-is-a-helper-box">
<p>I'm a helper!</p>
{{helperContents}}
</div>
</template>
This will work as a typical template, i.e. it can respond to events:
Template.helperTemplate.events({
'click .click-me': function(e, t) {
alert('CLICK!');
},
});
Finally, make a helper that will return this template.
Handlebars.registerHelper('blockHelper', function(options) {
return new Handlebars.SafeString(Template.helperTemplate({
helperContents: new Handlebars.SafeString(options.fn(this)),
}));
});
The helper options are passed as a helperContents param inside the template data. We used that param in the template to display the contents. Notice also that you need to wrap the returned HTML code in Handlebars.SafeString, both in the case of the template helper and its data.
Then you can use it just as intended:
<template name="example">
{{#blockHelper}}
Blah blah blah
<div class="click-me">CLICK</div>
{{/blockHelper}}
</template>

Related

How to properly find a conditionally rendered element from onRendered callback?

I’d like to find a conditionally rendered element after the template is rendered.
The template:
<template name="one">
<div class="normal">Normal</div>
{{#if active}}
<div class="conditional">Conditional</div>
{{/if}}
</template>
The code:
Template.one.onRendered(function() {
console.log(this.find(".normal"));
console.log(this.find(".conditional");
}
The above will log the ‘.normal’ but null for the ‘.conditional’ (the condition is true, both elements are present in the final DOM). The reason for that is well documented: onRender runs before {{#if}}s. But I want to run after the whole template is rendered, with all its {{#if}}s.
Is there a way to find that .conditional without making it a separate template?
I'm facing the same issue. This is because what's inside the {{#if}} block is rendered as a dynamically generated template.
So, the best workaround I've found so far is to render a specific template inside the {{#if}} block and add a callback to this specific template:
Here's what you should do:
<template name="one">
<div class="normal">Normal</div>
{{#if active}}
{{> activeTemplate}}
{{/if}}
</template>
<template name="activeTemplate">
<div class="conditional">Conditional</div>
</template>
Template.activeTemplate.onRendered(function() {
console.log(this.find(".conditional");
}
You won't find the DOM element because it doesn't exist.
It doesn't exist because active is false.
If you want active to return true:
Template.one.helpers({
"active": function() { return true; }
})

assemble - Render a list of strings as Handlebars partial

Using the assemble i actually stuck on a problem which i can't fix myself.
I'm defining a bunch of widgets in the YAML front matter section and including an partial aside {{> aside}}. Until here everything works as expected!
What i'm trying to do now, is to take the list widgets and rendering my partials within the aside template. But anyhow it does not work as expected.
src/templates/layouts/layout-default.hbs
---
layout: src/templates/layouts/layout-default.hbs
widgets:
- widget_link-list
- widget_welcome-message
---
<section role="main">
<h1>Template TwoCol</h1>
{{> body }}
</section>
<aside role="complementary">
{{> aside}}
</aside>
src/templates/partials/aside.hbs
{{#each widgets}}
{{.}}
{{/each}}
Using {{.}} prints my above defined list as string. But if i try to do {{> .}} this, the console drops the following warning:
Warning: The partial . could not be found Use --force to continue.
I found a way by creating a custom helper that can be invoked from any Handlebars template. Now i'm able to use {{renderPartial 'partialName' context}}.
In my template:
var aside = ['my-widget-a','my-widget-b','my-widget-x'];
{{#each aside}}
{{renderPartial this ../this}}
{{/each}}
Javascript Module
module.exports.register = function (Handlebars, context) {
Handlebars.registerHelper("renderPartial", function (name) {
var fn,
template = Handlebars.partials[name];
if (typeof template !== 'Function') {
// not compiled, so we can compile it safely
fn = Handlebars.compile(template);
} else {
// already compiled, just reuse it
fn = template;
}
var output = fn(context).replace(/^\s+/, '');
return new Handlebars.SafeString(output);
});
};

passing values to meteor partials

I'm learning meteor to build quick website prototypes.
I'm trying to understand how to generate a set of values to populate the site templates and partials.
I have a layout.html template
<template name="layout">
<div class="container">
<header role="banner">
{{>site-header}}
</header>
<h1>This is {{siteLogo}}</h1>
<main role="main">
{{ yield }}
</main>
<footer role="contentinfo">
{{> site-footer }}
</footer>
</div>
</template>
in main.js I define the following:
Meteor.startup(function(){
Session.set('siteLogo', 'the logo');
});
Template.site-header.helpers({
siteLogo: function(){ return Session.get('siteLogo'); }
});
Template.layout.helpers({
siteLogo: function(){ return Session.get('siteLogo'); }
});
With this i can pass the value of siteLogo to layout.html.
I have a site-header.html partial
<template name="site-header">
<h1>{{siteLogo}}</h1>
</template>
I can't seem to be able to pass the value of siteLogo to the partial. Is there a way to do that?
Is it necessary to create a Session variable to pre-fill some values or can i just create a json settings list and access the value globally?
something that would go in main.js, like the yaml config file in a jekyll site:
siteSettings = [
{
siteLogo: "some brand name",
otherValue: "something else"
}
]
update
I'm a bit confused, I'm must be doing something wrong.
I've created a quick new meteor app to test this.
I have main.html
<head>
<title>handlebar-helper</title>
</head>
<body>
{{> header}}
{{> hello}}
{{> footer}}
</body>
<template name="hello">
<h1>Hello World!</h1>
{{greeting}}
<input type="button" value="Click" />
</template>
<template name="header">
<header>
<h1>{{ headline }}</h1>
<p>tagline</p>
</header>
</template>
<template name="footer">
<footer role="contentinfo">
<h1>{{ headline }}</h1>
<small>copyright</small>
</footer>
</template>
And main.js
if (Meteor.isClient) {
Template.hello.greeting = function () {
return "Welcome to handlebar-helper.";
};
Template.hello.events({
'click input' : function () {
// template data, if any, is available in 'this'
if (typeof console !== 'undefined')
console.log("You pressed the button");
}
});
Meteor.startup(function(){
Session.set('headline', 'My fancy headline');
});
Handlebars.registerHelper('headline', function(){
return Session.get('headline');
});
}
if (Meteor.isServer) {
// server code here
}
And i can't still pass the value of headline into >header of >footer
if I try to put the Session.set into the Meteor.isServer block, I get a syntax error, Session is not defined
Cheers
Do you have a Template.site-header.helpers function declared for siteLogo? If not it won't work - you can't use a helper from another template. If you need to use siteLogo in a variety of places, it's best to use a Handlebars block helper, as these can be accessed by any template.
UPDATE
The Handlebars helper would just look like this:
Handlebars.registerHelper('siteLogo', function() {
return Session.get('siteLogo');
});
However, if you've already got a siteLogo helper in the site-header Template, it suggests something else is wrong, like a typo in a template or helper name. Is there an error in the console?
UPDATE 2
If you want to use a dictionary-style structure to store reactive data, you can do something like this:
Session.set('myDict', {foo: 1, bar: 2});
Handlebars.registerHelper('myDict', function(key) {
return Session.get('myDict') ? Session.get('myDict')[key] : null;
});
And then use this in your template: {{myDict 'foo'}}. Obviously, the format above would work fine in a tempate helper as well, but it would only be accessible from within that template. The ternary operator is just to check that myDict has been initialised before it lets a template try to look up one of the keys, which is a common Meteor problem on page load.
Incidentally, if you're finding Session variables a cumbersome way to deal with reactive dictionary-like data structures, it's pretty easy to roll your own. This is the best introduction.

Meteor template: Pass a parameter into each sub template, and retrieve it in the sub-template helper

I am trying to figure out how to pass a parameter into a sub-template that is in an each block and use the parameter in the sub-template as well as sub-template helper. Here is what I tried so far:
template:
<template name="parent">
{{#each nodes }}
{{> child myParam}}
{{/each}}
</template>
<template name="child">
{{ paramName }}
</template>
js:
Template.parent.nodes = function() {
//return a list
};
Template.parent.myParam = function() {
return {"paramName" : "paramValue"};
};
Template.child.someOtherHelper = function() {
//How do I get access to the "paramName" parameter?
}
So far, it hasn't been working, and it seems somehow mess up my input node list also.
Thanks for help.
When you use {{> child myParam}}, it's calling the child template and associates myParam as current template data context, meaning that in the template you can reference {{paramName}}.
In someOtherHelper you could use this.paramName to retrieve "paramValue".
However, when you're using {{#each nodes}}{{> child}}{{/each}}, it means that you pass the content of the current list item (fetched from a LocalCursor or directly an array item) as the template data of child, and you can reference the list item properties using {{field}} in html or this.field in js.
What's happening here is when you call {{> child myParam}}, the myParam helper content OVERWRITES the current node item as template data, that's why it's messing your node list.
A quick (dirty) trick would be to simply extend the myParam helper so that it also contains the template data from the {{#each}} block.
Template.parent.helpers({
nodes:function(){
// simulate typical collection cursor fetch result
return [{_id:"A"},{_id:"B"},{_id:"C"}];
},
myParam:function(){
// here, this equals the current node item
// so we _.extend our param with it
return _.extend({paramName:"paramValue"},this);
}
});
Template.child.helpers({
someOtherHelper:function(){
return "_id : "+this._id+" ; paramName : "+this.paramName;
}
});
<template name="parent">
{{#each nodes}}
{{> child myParam}}
{{/each}}
</template>
<template name="child">
{{! this is going to output the same stuff}}
<div>_id : {{_id}} ; paramName : {{paramName}}</div>
<div>{{someOtherHelper}}</div>
</template>
Depending on what you're precisely trying to achieve, there might be a better approach but this one gets the job done at least.

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