Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 678
aw04 Avatar asked Apr 01 '16 15:04

aw04


1 Answers

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"] 
 }
like image 152
Arthur Avatar answered Oct 16 '22 06:10

Arthur