Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I register a custom function? #7

Closed
jakejscott opened this issue Aug 4, 2016 · 3 comments
Closed

How do I register a custom function? #7

jakejscott opened this issue Aug 4, 2016 · 3 comments
Labels

Comments

@jakejscott
Copy link

No description provided.

@jakejscott
Copy link
Author

I worked it out 👍

var script = new ScriptObject();
script.Import(model);
script.SetValue("custom", ScriptObject.From(typeof(CustomFunctions)), true);

TemplateContext context = new TemplateContext();
context.PushGlobal(script);

Template template = Template.Parse(html);
template.Render(context);
context.PopGlobal();

string rendered = context.Output.ToString();

@xoofx
Copy link
Member

xoofx commented Aug 5, 2016

your solution imports all public functions from CustomFunctions into an object and associate it to the custom variable (so it is more import multiple functions!)

You may also use ScriptObject.Import(name, delegate) (or use a new Func<...>(function) as a delegate) in case you want to import a specific function or a this/closure function.

@xoofx xoofx closed this as completed Aug 5, 2016
@xoofx xoofx added the question label Aug 5, 2016
@jakejscott
Copy link
Author

jakejscott commented Aug 5, 2016

Which looks like this if anyone struggles with Func syntax like I do :)

Func<double, string> currency = value => value.ToString("C");
script.Import("currency", currency);

// Or like this.
script.Import("currency", (Func<double, string>)(value => value.ToString("C")));

And in your template

<p>
Subtotal: {{ order.sub_total_price | currency }} {{ order.currency }} <br />
</p>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants