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?
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.
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}}
Handlebars: What it is and Why to Use itHandlebars is a logic-less templating engine that dynamically generates your HTML page.
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}} .
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 ''; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With