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.
Meteor Newbie here!
I have a page where all the open orders are displayed. The order details are stored in a collection. A Template helper will return the order details.
Template.delivery.helpers({
openOrders: function(){
return Orders.find({status: "open"});
}
});
The template look some what like this.
{{#if openOrders}}
{{#each openOrders}}
Date: {{createdAt}}
Total items: {{items.length}}
Location: {{location}} //It prints the location _id
{{/each}}
{{/if}}
The Order Collection only have the _id of the location. The Location details are stored in a Collection named Locations.
I want to display the location name (which is stored in the Location collection) instead of the _id.
I created a Template helper which returns the Location details, but how can I link these to helpers so that the Location name is displayed instead of Location _id?
As you're using mongodb in a relational database fashion, you need to install publish-composite package to make sure all the necessary data are subscribed.
When you use each, it will set the this to the current thing that is being iterated over. This will allow you to use this in your helper to perform lookups. So in this case, if you're using a helper to get the orders:
orders: function () {
return Orders.find({ status: "orders" });
}
Then when you iterate over it with {{#each}}, this is set to the current order, meaning your location helper with look like this:
location: function () {
return Locations.findOne(this.locationId);
}
Putting it all together in the template it would be like:
{{#if Template.subscriptionsReady}}
{{#each orders}}
<h1 class="title">Order #{{_id}}</h1>
{{#with location}}
<div class="location">
<span>Latitude: {{ latitude }}</span>
</div>
{{/with}}
{{/each}}
{{/if}}
Keep in mind: this will only work if you also publish your locations.
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.
In my ember application I have defined a select element like this in my template:
{{view Ember.Select
content=greetings
optionValuePath="content.id"
optionLabelPath="content.code"
value=selectedGreeting
selection=selectedGreeting
prompt="Please choose"}}
The controller for this page (shared form and controller for create and edit form) looks like this:
greetings: [
{code: "Mr.", id: 1},
{code: "Mrs.", id: 2}
],
selectedGreeting: null,
actions: {
save: function(){
var person = this.get('model');
if (person == null || person.id == undefined)
{
// create mode
var greeting = this.selectedGreeting.id;
// ....
var newPerson = this.get('store').createRecord('person',{
greeting: greeting,
// ..
});
newPerson.save();
this.transitionToRoute('index');
}
else
{
// edit mode
person.set('greeting', this.selectedGreeting.id);
person.save();
}
}
}
This works perfect when creating a new person, but when opening an existing one the select box shows the promt instead of the saved value (do I really have to do this with jQuery?).
Besides I suppose there must be an easier way to update the existing model with the selected values in the else branch, as the other properties get modified automagically.
Any suggestions would be appreciated, the documentation for Ember unfortunately does not help a lot in this case.
The Ember.Select view has quite a few quirks. In fact, if I remember correctly, I saw an issue on Github to just have the whole thing rewritten. For now, I'm assuming that the prompt attribute takes precedence over the selection attribute. To get around that, I would just use a conditional in the template.
{{#if model}}
{{view Ember.Select ... value=selectedGreeting}}
{{else}}
{{view Ember.Select ... prompt='Please Choose'}}
{{/if}}
Also, your second question, if I understand you correctly, you should be able to just use selection=model.greeting to bind the selection value to the model property. And if you're using the template above, you can make it so it only applies to the former and not the latter.
I got it fixed using:
{{view Ember.Select
content=greetings
optionValuePath="content.id"
optionLabelPath="content.code"
value=model.greeting
prompt="Please select"
}}
This works in both ways - loading the data from model and saving the data to the model. The prompt does not interfere with the value from what I experienced.
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"}]'
}}