Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array written in template to meteor/handlebars helper

Tags:

I have a helper called printArray that just prints every item in an array. It works great when I define the array in JS and pass it in to the helper via a context object. What I want to do is define the array right in the template, like:

{{printArray arr=[1, 3, 4] }} 

Unfortunately, by the time this gets to my helper, the arr key points to undefined. Is there any valid syntax to get the array inside my helper without defining it in javascript?

like image 835
Riley Lark Avatar asked May 28 '13 03:05

Riley Lark


People also ask

Is handlebars a template language?

Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions.

What is helper in handlebars?

A Handlebars helper call is a simple identifier, followed by zero or more parameters (separated by a space). Each parameter is a Handlebars expression that is evaluated exactly the same way as described above in "Basic Usage": template {{firstname}} {{loud lastname}}

Is handlebars a template engine?

Handlebars: What it is and Why to Use itHandlebars is a logic-less templating engine that dynamically generates your HTML page.

Can you use JavaScript in handlebars?

Handlebars doesn't allow you to write JavaScript directly within templates. Instead, it gives you helpers. These are JavaScript functions that you can call from your templates, and help you reuse code and create complex templates. To call a helper, just use it as an expression - {{helpername}} .


1 Answers

You can use JavaScript's arguments array to accomplish something like this. The arguments array gives you access to every value passed to the function when it is called.

This will allow you to use syntax like this:

{{printArray 1 3 4}} 

The code looks like this:

Handlebars.registerHelper('printArray', function() {     //Last argument is the options object.     var options = arguments[arguments.length - 1];      //Skip the last argument.     for(var i = 0; i < arguments.length - 1; ++i) {         //Do your thing with each array element.     }      //Return your results...     return ''; }); 
like image 108
AaronSieb Avatar answered Sep 21 '22 14:09

AaronSieb