axuno / SmartFormat

A lightweight text templating library written in C# which can be a drop-in replacement for string.Format
Other
1.09k stars 104 forks source link

How to nest/chain custom formatters? #91

Closed drmcclelland closed 7 years ago

drmcclelland commented 7 years ago

I've created a couple of custom formatters which work well independently. However, I'd like to nest or chain them together - basically take OUTPUT of formatter1 and provide that as the INPUT to formatter2. Is there already supported syntax for this?

I tried these and it didn't work for me:

My workaround was to create a single formatter that took multiple parameters and combined the functionality of formatter1 and formatter2 together.

This is a really great library, makes things a lot easier for our application!

axunonb commented 7 years ago

Yes, nesting would indeed be nice - but a lot of things to consider for a general approach. Would you expect that parsing would take place only once, i.e. without reparsing the result of the previous step for any placeholders?

drmcclelland commented 7 years ago

I agree - this would take some thought as to what the "expected behavior" would be. Being the newbie that I am to SmartFormat.NET, I have not had to handle any advanced use cases for formatting beyond numeric conversions, and truncating strings to fit in fixed-width fields.

ericpyle commented 7 years ago

Another chaining example?

{boolVal1:or({boolVal2}:or({boolVal3})): passes | fails}

Not sure if that's the best approach. Obviously the model data could be made to have a field that is essentially boolVal1OrBoolVal2OrBoolVal3. But data mining capability in a template is helpful as well.

axunonb commented 7 years ago

In general my way of thinking is to keep the business logic in the code. When it comes to testing, this brings a lot of benefits. What Smart.Formatis aiming at is to achieve a desired output very fast with only little coding, and with minimal logic in the formatters. This way, the text templates can still be prepared by authors rather than by programmers. As soon as it comes to implementing program logic, solutions like the Razor Engine (https://github.com/Antaris/RazorEngine) may be a better fit. But this flexibility goes at the cost of testing efforts and performance.