Nustache icon indicating copy to clipboard operation
Nustache copied to clipboard

Custom helpers not available in Template

Open muxa opened this issue 6 years ago • 1 comments

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?

muxa avatar Sep 10 '18 04:09 muxa

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.

zoka-cz avatar Oct 31 '19 10:10 zoka-cz