Handlebars Partial Data with Dot Notation - javascript

In Handlebars, I need to overwrite partial data that data is scoped within a JS object.
The index.hbs file renders multiple partials with different data, but the module properties need to be scoped within the global data object. Overwriting partial attributes using dot notation fails to compile.
Index.hbs
<body>
{{> User }}
{{> User user.name="laura" }} // fails to compile - how to overwrite?
</body>
User.hbs
<div>
Name is: {{name}}
Location is: {{location}}
</div>
Index.js
import index from "Index.hbs";
import user_partial from "User.hbs";
data = {
user: {
name: "kevin",
location: "bar"
}
}
Handlebars.registerPartial(user, user_partial);
document.innerHTML = Handlebars.compile(index)(data);

The documentation says that contexts are passed to the partial like {{> myPartial myOtherContext }} and that additional parameters are passed like {{> myPartial parameter=favoriteNumber }}.
Therefore, it seems you could achieve your objective by passing user as the context and the overrides as parameters. Your template would become:
{{> User user }}
{{> User user name="laura" }}
I have created a fiddle for reference.

Related

Pass object literal to handlebars partial

Is it possible to do something like the following in a handlebars template?
{{> myPartial {name: 'steve', age: '40'} }}
This throws a parse error on {. I'm fine with passing either a context or named parameter.
docs:
It's possible to execute partials on a custom context by passing in the context to the partial call.
{{> myPartial myOtherContext }}
I'm using webpack with handlebars-loader to render my templates and I don't really have anywhere to pass in a context. I simply want to use this partial in multiple templates and specify the data at that time.
Related to this reply : https://github.com/wycats/handlebars.js/issues/476 You cannot assign new variable on Handlebars template, you must create this object {name: 'steve', age: '40'} on template data.
data.user = {name: 'steve', age: '40'}
on .hbs
{{> myPartial user}}
But you can take a look to private variables : http://handlebarsjs.com/block_helpers.html
---- UPDATE August 2017 ----
With the new let block helper instruction you can create HTML variable to manipulate easier your display logic:
Global JS
// Create a new Global helper, available everywhere
Template.registerHelper('getUser', function () {
return Meteor.user()
})
Blaze HTML
Use your global helper to retrieve the user into a variable and use it into HTML
{{#let user=getUser}}
{{#if user}}
Hi {{user.name}}
{{else}}
Please Login
{{/if}}
{{/let}}
---- UPDATE 2019 ----
Let reopen that question and put it to the next level.
By registering new simple helpers you will be able to create object or array directly from Blaze (so everything you want):
Template.registerHelper('object', function({hash}) {
return hash;
})
Template.registerHelper('array', function() {
return Array.from(arguments).slice(0, arguments.length-1)
})
Usage:
{{> myPartial (object name="steve" age=40 array_example=(array true 2 "3"))}}
Will send as context:
{
name: 'steve',
age: 40,
array_example: [true, 2, "3"]
}
register a helper (i.e. context) for parsing the context you want to pass:
here is how: https://jsfiddle.net/dregep/o4p1g8nL/11/
Handlebars.registerHelper('context', function (jsString) {
return eval("context=" + jsString);
});
then call it like this:
{{> myPartial (context 'js object') }}
example:
{{> myPartial (context '{a: 1}') }}
this is equivalent to:
{{> myPartial a=1 }}

Meteor.js using value of a helper as template

I would like to render different template based on a helper value. I will try to write and example.
...
{{#with myHelper}}
{{> this }}
{{/with}}
...
with the helper define like this for example:
...
myHelper : function(){
return MyCollection.findOne({ userId: Meteor.userId() }).personalizeTemplate;
}
...
Unfortunately in this way doesn't work. There could be any solution for that?
You need to use a dynamic template You don't even need the {{#with}}
{{> Template.dynamic template=myHelper }}
To use templates dynamically you have to use the global Template.dynamic :
{{> Template.dynamic template="my template"}}
{{> Template.dynamic template=myHelper}}
Note that myHelper must return a String which is the name of the template.
You may also provide a data context with data :
{{> Template.dynamic template=myTemplate data=someData}}
Discover Meteor wrote an article about it. It was created back in 2014 and the UI namespace used throughout the article has since been renamed Template.

Accessing parent helper in Meteor

I often find myself dividing my work into templates that still could use the same helpers.
So, say I have this template structure:
<template name="MainTemplate">
<div>{{> FirstTemplate}}</div>
<div>{{> SecondTemplate}}</div>
<div>{{> ThirdTemplate}}</div>
<div>{{> FourthTemplate}}</div>
</template>
Now each of these templates wants to use the same helper, let's call it dataHelper:
Template.MainTemplate.helpers({
dataHelper: function() {
//do some stuff
return result
}
})
Sadly, this helper can't be accessed in template first through fourth by simply typing {{dataHelper}} like how events work.
My solution has been to create a global helper instead, but that seems a tad overkill, especially since I have a few pages that don't care about these helpers at all. Another solution is to create four separate helpers but, hey, DRY.
Am I missing something simple here?
There isn't an obvious way to do this in the current version of meteor. One solution is for the child template to "inherit" the helpers from the parent. You can do this pretty easily using meteor-template-extension. Here's an example:
html
<body>
{{> parent}}
</body>
<template name="parent">
<h1>parent</h1>
{{> child}}
</template>
<template name="child">
<h2>child</h2>
<p>{{saySomething}}</p>
</template>
js
Template.parent.helpers({
saySomething: function() {
return Random.choice(['hello', 'dude!', 'i know right?']);
}
});
Template.child.inheritsHelpersFrom('parent');
The template child inherits all of its parent's helpers so it has direct access to saySomething.
This technique has two drawbacks:
you have to specify the inheritsHelpersFrom relationship
all of the parent's helpers are inherited
You can access your parent helpers using either a notation like {{yourParentHelper ..}} with two dots. Have a look here for more informations (end of the article)
You can also access parent data context in javascript like that:
var parent_data = Template.parentData();
By the way, you can add a parameter to reach the third parent, for instance:
var parent_data = Template.parentData(3);
The double dot notation seems to work best within {{#each}} loops, and I'm not having any luck within actual child templates. One option would be to use {{#with}}, although that limits you to basically one helper. e.g.:
<template name="parent">
{{#with dataHelper}}
{{> first}}
{{> second}}
{{/with}}
</template>
This will set the data context of the child helpers to dataHelper, and you can access them with {{this}} inside the template. I suppose you could make dataHelper an object and then pass in multiple pieces of data that way.

How valueBinding works in Ember?

Honestly i didn't find much helpful guides on emberjs.com about valueBindings.
//login_route.js
App.LoginRoute = Ember.Route.extend({
model: function() {
return Ember.Object.create();
}
});
Basically here i'm creating empty JS object to be model for login template.
//login.hbs
...
{{view Em.TextField valueBinding="email" id="email"}}
{{view Ember.TextField valueBinding="password" type="password" id="password"}}
...
So when user start to type user&pass, behind the scenes, Ember will crate 2 properties named "email" and "password" and 'append' them to context(model) of the current template and properties will be constantly updated till user hit login button ?
I can guess that is correct because i can do simple debug inside template:
{{ email }} (which is equal to {{ controller.email }} which again is equal to {{ controller.model.email }})?
valueBinding essentially is telling Ember to bind the property named password to the internal property in Ember.TextField named value.
additionally you can just bind it to the property, like so
{{view Em.TextField value=email id="email"}}
http://emberjs.jsbin.com/xujugayo/1/edit
Now the reason that
{{ controller.email }} is equal to {{ controller.model.email }} because the controller backing your template is an ObjectController. The ObjectController is a proxy object, meaning it will proxy properties from the model that's backing it, as if they were on the controller.

Passing variables through handlebars partial

I'm currently dealing with handlebars.js in an express.js application. To keep things modular, I split all my templates in partials.
My problem: I couldn't find a way to pass variables through an partial invocation. Let's say I have a partial which looks like this:
<div id=myPartial>
<h1>Headline<h1>
<p>Lorem ipsum</p>
</div>
Let's assume I registered this partial with the name 'myPartial'. In another template I can then say something like:
<section>
{{> myPartial}}
</section>
This works fine, the partial will be rendered as expected and I'm a happy developer. But what I now need, is a way to pass different variables throught this invocation, to check within a partial for example, if a headline is given or not. Something like:
<div id=myPartial>
{{#if headline}}
<h1>{{headline}}</h1>
{{/if}}
<p>Lorem Ipsum</p>
</div>
And the invokation should look something like this:
<section>
{{> myPartial|'headline':'Headline'}}
</section>
or so.
I know, that I'm able to define all the data I need, before I render a template. But I need a way to do it like just explained. Is there a possible way?
Handlebars partials take a second parameter which becomes the context for the partial:
{{> person this}}
In versions v2.0.0 alpha and later, you can also pass a hash of named parameters:
{{> person headline='Headline'}}
You can see the tests for these scenarios: https://github.com/wycats/handlebars.js/blob/ce74c36118ffed1779889d97e6a2a1028ae61510/spec/qunit_spec.js#L456-L462
https://github.com/wycats/handlebars.js/blob/e290ec24f131f89ddf2c6aeb707a4884d41c3c6d/spec/partials.js#L26-L32
Just in case, here is what I did to get partial arguments, kind of. I’ve created a little helper that takes a partial name and a hash of parameters that will be passed to the partial:
Handlebars.registerHelper('render', function(partialId, options) {
var selector = 'script[type="text/x-handlebars-template"]#' + partialId,
source = $(selector).html(),
html = Handlebars.compile(source)(options.hash);
return new Handlebars.SafeString(html);
});
The key thing here is that Handlebars helpers accept a Ruby-like hash of arguments. In the helper code they come as part of the function’s last argument—options— in its hash member. This way you can receive the first argument—the partial name—and get the data after that.
Then, you probably want to return a Handlebars.SafeString from the helper or use “triple‑stash”—{{{— to prevent it from double escaping.
Here is a more or less complete usage scenario:
<script id="text-field" type="text/x-handlebars-template">
<label for="{{id}}">{{label}}</label>
<input type="text" id="{{id}}"/>
</script>
<script id="checkbox-field" type="text/x-handlebars-template">
<label for="{{id}}">{{label}}</label>
<input type="checkbox" id="{{id}}"/>
</script>
<script id="form-template" type="text/x-handlebars-template">
<form>
<h1>{{title}}</h1>
{{ render 'text-field' label="First name" id="author-first-name" }}
{{ render 'text-field' label="Last name" id="author-last-name" }}
{{ render 'text-field' label="Email" id="author-email" }}
{{ render 'checkbox-field' label="Private?" id="private-question" }}
</form>
</script>
Hope this helps …someone. :)
This can also be done in later versions of handlebars using the key=value notation:
{{> mypartial foo='bar' }}
Allowing you to pass specific values to your partial context.
Reference: Context different for partial #182
This is very possible if you write your own helper. We are using a custom $ helper to accomplish this type of interaction (and more):
/*///////////////////////
Adds support for passing arguments to partials. Arguments are merged with
the context for rendering only (non destructive). Use `:token` syntax to
replace parts of the template path. Tokens are replace in order.
USAGE: {{$ 'path.to.partial' context=newContext foo='bar' }}
USAGE: {{$ 'path.:1.:2' replaceOne replaceTwo foo='bar' }}
///////////////////////////////*/
Handlebars.registerHelper('$', function(partial) {
var values, opts, done, value, context;
if (!partial) {
console.error('No partial name given.');
}
values = Array.prototype.slice.call(arguments, 1);
opts = values.pop();
while (!done) {
value = values.pop();
if (value) {
partial = partial.replace(/:[^\.]+/, value);
}
else {
done = true;
}
}
partial = Handlebars.partials[partial];
if (!partial) {
return '';
}
context = _.extend({}, opts.context||this, _.omit(opts, 'context', 'fn', 'inverse'));
return new Handlebars.SafeString( partial(context) );
});
Sounds like you want to do something like this:
{{> person {another: 'attribute'} }}
Yehuda already gave you a way of doing that:
{{> person this}}
But to clarify:
To give your partial its own data, just give it its own model inside the existing model, like so:
{{> person this.childContext}}
In other words, if this is the model you're giving to your template:
var model = {
some : 'attribute'
}
Then add a new object to be given to the partial:
var model = {
some : 'attribute',
childContext : {
'another' : 'attribute' // this goes to the child partial
}
}
childContext becomes the context of the partial like Yehuda said -- in that, it only sees the field another, but it doesn't see (or care about the field some). If you had id in the top level model, and repeat id again in the childContext, that'll work just fine as the partial only sees what's inside childContext.
The accepted answer works great if you just want to use a different context in your partial. However, it doesn't let you reference any of the parent context. To pass in multiple arguments, you need to write your own helper. Here's a working helper for Handlebars 2.0.0 (the other answer works for versions <2.0.0):
Handlebars.registerHelper('renderPartial', function(partialName, options) {
if (!partialName) {
console.error('No partial name given.');
return '';
}
var partial = Handlebars.partials[partialName];
if (!partial) {
console.error('Couldnt find the compiled partial: ' + partialName);
return '';
}
return new Handlebars.SafeString( partial(options.hash) );
});
Then in your template, you can do something like:
{{renderPartial 'myPartialName' foo=this bar=../bar}}
And in your partial, you'll be able to access those values as context like:
<div id={{bar.id}}>{{foo}}</div>
Yes, I was late, but I can add for Assemble users: you can use buil-in "parseJSON" helper http://assemble.io/helpers/helpers-data.html. (Discovered in https://github.com/assemble/assemble/issues/416).
Not sure if this is helpful but here's an example of Handlebars template with dynamic parameters passed to an inline RadioButtons partial and the client(browser) rendering the radio buttons in the container.
For my use it's rendered with Handlebars on the server and lets the client finish it up.
With it a forms tool can provide inline data within Handlebars without helpers.
Note : This example requires jQuery
{{#*inline "RadioButtons"}}
{{name}} Buttons<hr>
<div id="key-{{{name}}}"></div>
<script>
{{{buttons}}}.map((o)=>{
$("#key-{{name}}").append($(''
+'<button class="checkbox">'
+'<input name="{{{name}}}" type="radio" value="'+o.value+'" />'+o.text
+'</button>'
));
});
// A little test script
$("#key-{{{name}}} .checkbox").on("click",function(){
alert($("input",this).val());
});
</script>
{{/inline}}
{{>RadioButtons name="Radio" buttons='[
{value:1,text:"One"},
{value:2,text:"Two"},
{value:3,text:"Three"}]'
}}

Categories