简体   繁体   中英

How to pass custom helper function as a context to handlebars template?

I am new to handlebars and I want to know how to pass a custom helper as a context to the views template ( if that is possible )? The case is: I have an array of 5 elements and a template with 5 tags, I want to render the template in such a way that it is in the order of the array passed. Example: if I pass an array as [2,1,3,4,5] then I want the divs to be rendered in that order; that is second div, then first div, then third div, then fourth div and then the fifth div. I declared the helper function in the controller file as

Handlebars.RegisterHelper('check',(a,b)=>{
     return a.toString()===b  
})

My handlebars file is like this:

<html>
.
.
.
<div id='one'></div>
<div id='two'></div>
<div id='three'></div>
<div id='four'></div>
<div id='five'></div>
.
.
.
</html>

My question is when I pass an array [2,1,5,4,3], I want to render the div in that order that is div with id 'two' then div with id 'one' and like that.

I think that if I had more context around what you want to achieve then I might suggest an alternative approach. However, based on the information you have given, I do have a suggested approach.

I think you should not use a helper, but instead use Handlebars Partials for each of the unique div templates you want to define.

Then, in the context object you pass to your template, you can supply an array of the partials names you want to include, in the order in which you want to include them.

Assuming you have registered partials named "one", "two", "three", "four", "five", your array might look like ["two", "one", "three", "four", "five"] .

Your template would then iterate through each partial name and use Dynamic Partial resolution to include the correct partial.

Handlebars will not let you to directly pass a variable containing the name to the dynamic partial resolution, so you will need to a lookup . Assuming the array of partial names is given the identifier partials , the resulting template would look like:

{{#each partials}}
    {{> (lookup ../partials @index)}}
{{/each}}

I have created a fiddle for your reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM