Handlebars-Net / Handlebars.Net

A real .NET Handlebars engine
MIT License
1.24k stars 214 forks source link

Access parent context in a custom helper #469

Closed jamesfarrugia96 closed 2 years ago

jamesfarrugia96 commented 2 years ago

Is it possible to access the parent context within a helper? For example, I need to access properties in the parent context from a custom helper that is called within the {{#each}} helper. Thanks

example:

var model = {text: hello, lines=[{x:10}, {x:20}, {x:30}]

{{text}} {{#each lines}} {{customHelper x}} {{/each}}

Is it possible to be able to access the model.text property in the implementation of customHelper please?

jamesfarrugia96 commented 2 years ago

Any suggestions please? :)

oformaniuk commented 2 years ago

Hello @jamesfarrugia96

Yes, it's possible. You should use the following overload:

void RegisterHelper(string helperName, HandlebarsHelperWithOptions helperFunction)

Delegate HandlebarsHelperWithOptions gives you an access to HelperOptions instance which provides access to data property. Access to parent would look something like this: options.Data["parent"].

As far as I can see mentioned overload is not exposed through Handlebars.RegisterHelper (aka static method), so you'd need to do Handlebars.Create() in order to access that overload. I'd appreciate a PR to fix this mismatch and introduce the overload as a static method as well.

jamesfarrugia96 commented 2 years ago

Thanks @zjklee will look into it and give you another update :)

jamesfarrugia96 commented 2 years ago

HI @zjklee, will be pushing a PR to introduce the static methods for the HelperWithOptions overloads. For those accessing the helpers with Handlebars.Create(), should I leave the delegate methods as they are, or shall I remove the in keyword inline with the other delegates? (see attached screenshot for reference):

image

oformaniuk commented 2 years ago

HI @zjklee, will be pushing a PR to introduce the static methods for the HelperWithOptions overloads. For those accessing the helpers with Handlebars.Create(), should I leave the delegate methods as they are, or shall I remove the in keyword inline with the other delegates? (see attached screenshot for reference):

image

Hello @jamesfarrugia96 in should stay there as it's an optimization for struct parameters. I kept existing methods without in for the sake of backward compatibility. Looking forward to see the PR 😄