Nustache
Nustache copied to clipboard
Custom helpers not available in Template
I'm getting an error Nustache.Compilation.CompilationException : Could not find formatDateTime Timestamp format="dd/MM/yyyy hh:mm tt"
Code:
[Test]
public void NustacheTest()
{
Nustache.Core.Helpers.Register("FormatDateTime", FormatDateTime);
var template = new Template();
using (var sr = new StreamReader("template.mustache"))
{
template.Load(sr);
}
var compiled = template.Compile<TopupReceiptModel>(null);
var result = compiled(new { Timestamp = DateTime.Now });
Console.WriteLine(result);
}
public static void FormatDateTime(RenderContext context, IList<object> arguments, IDictionary<string, object> options, RenderBlock fn, RenderBlock inverse)
{
if (arguments != null && arguments.Count > 0 && arguments[0] != null && arguments[0] is DateTime)
{
DateTime datetime = (DateTime)arguments[0];
if (options != null && options.ContainsKey("format"))
context.Write(datetime.ToString(options["format"] as string));
else
context.Write(datetime.ToString());
}
}
Template:
Transaction Details
Date & Time {{ FormatDateTime Timestamp format="dd/MM/yyyy hh:mm tt"}}
If a remove FormatDateTime
helper from the template and just use Timestamp
it works.
Can somebody help please?
See the remark from the project description:
All arguments and options are separated by spaces and even closed in double-quotes they cannot contain spaces.
Your format contains spaces, which is forbidden. You have to find other way, like some masking of spaces to other characters and replacing them in the FormatDateTime function.