Pass object literal to handlebars partial
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"]
}
aw04
Updated on July 25, 2022Comments
-
aw04 almost 2 years
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.
-
Arthur about 5 yearsI read your answer when i came here to update mine, you should look at my both new helpers (
object
andarray
), they may interest you. Eval is overkill -
Miguel Sánchez Villafán over 3 yearsIn the 2019 update, Why would you slice the array after creating an array from the arguments? Isn't it copying the array twice?
-
Miguel Sánchez Villafán over 3 yearsTurns out that handlebars sends an additional parameter so you're removing it. Although I think performance-wise, it would be better to save it in a variable and removing the last element rather then copying all elements again except for the last one
-
MeV about 3 yearsThanks your answer helped a lot!