简体   繁体   中英

How to create custom money filters in Dot Liquid & C#?

I am using Dot Liquid to create HTML templates in a C# application. As of now I am displaying numbers to some table cells that I get from a JSON array but I want the numbers to be seperated with a thousands delimiter. For example the number I get from JSON is 40000.50 and I want it to look like this : 40.000,50 with a filter. Unfortunately Dot Liquid's implementation of standard filters is a little bit poor when it comes to customizing numbers. (Also for some reason the money filter does not work in my case). I was wondering if anyone has any idea on how to create a custom filter with C# or if I can somehow use an existing custom filter for my purposes.

You can register custom value formatter and pass to it Culture with correct decimal and group separator. Pay attention that value formatter is global and will be applied to all templates.

var clone = (CultureInfo)CultureInfo.InvariantCulture.Clone();
clone.NumberFormat.CurrencyDecimalSeparator = ",";
clone.NumberFormat.CurrencyGroupSeparator = ".";
clone.NumberFormat.CurrencySymbol = "";
Template template = Template.Parse("Format example {{money}}");
Template.RegisterValueTypeTransformer(typeof(decimal), (v) => ((decimal)v).ToString("C", clone));
var result = template.Render(Hash.FromAnonymousObject(new { money = 40000.50m }));

Example: https://dotnetfiddle.net/EpLe1J

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM