Handlebars.Net icon indicating copy to clipboard operation
Handlebars.Net copied to clipboard

Is is possible to provide helpers when the template is being rendered?

Open markdebhailis opened this issue 3 years ago • 2 comments

Using this sample as a reference https://github.com/Handlebars-Net/Handlebars.Net#registering-helpers

I would like to pass the helper implementation to the template e.g. here's some psuedo code

string source = @"Click here: {{link_to}}";

var template = Handlebars.Compile(source);

HandlebarsHelper link_to = "link_to", (writer, context, parameters) => 
{
    writer.WriteSafeString($"<a href='{context["url"]}'>{context["text"]}</a>");
};

var data = new {
    url = "https://github.com/rexm/handlebars.net",
    text = "Handlebars.Net",
    link_to = link_to
};

var helpers = new {
    link_to = x)
};

var result = template(data);

The above outputs Click here: HandlebarsDotNet.HandlebarsHelper but I want it to recognise that 'link_to' is a helper.

I know it's possible to register the helper after the template is compiled but I want to be able scope the function to a single template render operation.

markdebhailis avatar Oct 23 '23 21:10 markdebhailis

No, it is not possible at the moment. I'd be happy to see PR enabling such behavior.

oformaniuk avatar Apr 01 '24 02:04 oformaniuk

Helpers must be registered on the IHandlebars instance (or the static Handlebars class) before or after compilation — but not injected at render time. If you need different helpers per render, create separate IHandlebars instances with Handlebars.Create() and register the appropriate helpers on each. Closing as this is by design.

rexm avatar Jun 20 '26 17:06 rexm