Skip to content
axunonb edited this page Mar 12, 2022 · 110 revisions

What is SmartFormat?

SmartFormat is a lightweight text templating library written in C#.

It can format various data sources into a string with a minimal, intuitive syntax similar to string.Format. All formatting takes place at runtime.

SmartFormat uses extensions to provide named placeholders, localization, pluralization, gender conjugation, as well as list and time formatting. Formatting extensions can be nested.

Custom source or formatter extensions can be added easily using simple interfaces.

Features

  • High performance with low memory footprint
  • Minimal, intuitive syntax
  • Formatting takes place exclusively at runtime
  • Exact control of whitespace text output
  • string.Format compatibility mode and Smart.Format enhanced mode
  • Most common data sources work out-of-the-box
  • Many built-in formatting extensions
  • Custom formatting and source extensions are easy to integrate
  • Comprehensive documentation: current Wiki, complete xmldoc

Show me some examples

1. A very simplistic example:

var data = new { Library = "SmartFormat"};
_ = Smart.Format("Composed with {Library}.", data);
// Result: "Composed with SmartFormat."

2. Example in string.Format style:

var stringFormat = string.Format("{0} {0:N2} {1:yyyy-MM-dd}", 5, new DateTime(1900, 12, 31));
var smartFormat = Smart.Format("{0} {0:N2} {1:yyyy-MM-dd}", 5, new DateTime(1900, 12, 31));
// Result: (stringFormat == smartFormat) == true

3. Example how to format an IList:

var data = new [] {1, 2, 3, 4, 5};
_ = Smart.Format("{0:list:N2|, |, and }.", (object) data);
// Result: "1.00, 2.00, 3.00, 4.00, and 5.00."

4. Example for choosing an output string depending on a value:

var data = new[]  { new { Name = "John", Gender = 0 }, 
                    new { Name = "Mary", Gender = 1 } };
_ = Smart.Format("{Name} commented on {Gender:choose:his|her} photo", data[1]);
// Result: "Mary commented on her photo"

5. An a bit more complex appetizer

Formatters can be nested. In this example we have

  • a ListFormatter
  • with a nested ListFormatter
  • which has a nested DefaultFormatter
var data = new List<int[]> {
    new[] { 1, 2, 3 },
    new[] { 4, 5, 6 },
    new[] { 7, 8, 9 }
};
// "list" is the formatter name
_ = Smart.Format("{0:list:Elements\\: {:list:{:000}|, |, }|\n|\n}", data);
//                |                   |        | |       |      |
//                |                   |  element format  |      |
//                |                   |___ inner list ___|      |
//                |_______________________ outer list __________|
/* Result:
Elements: 001, 002, 003
Elements: 004, 005, 006
Elements: 007, 008, 009
*/

... and there's much more SmartFormat can do.

Keep on reading.

Clone this wiki locally