-
-
Notifications
You must be signed in to change notification settings - Fork 104
v2 Creating your own extension
public class HelloFormatter : IFormatter
{
private string[] names = new[] {"hello", "hi"};
public string[] Names { get { return names; } set { this.names = value; } }
public bool TryEvaluateFormat(IFormattingInfo formattingInfo)
{
var iCanHandleThisInput = formattingInfo.CurrentValue is bool;
if (!iCanHandleThisInput)
return false;
formattingInfo.Write("HELLO ");
if ((bool) formattingInfo.CurrentValue)
formattingInfo.Write(formattingInfo.FormatterOptions);
else
formattingInfo.Write(formattingInfo.Format.GetLiteralText());
return true;
}
}
Smart.Default.AddExtensions(new HelloFormatter());
Smart.Format("{value:hello(world):earth}", new { value = true });
// Outputs: "HELLO world"
Smart.Format("{value:hi(world):earth}", new { value = false });
// Outputs: "HELLO earth"
A Format String is the template that defines how the data should be formatted.
Let's analyze the following Format String:
"The user {Name} was born in {Birthday:MMMM}, is {Age:000} {Age:year|years} old, and lives in {Address.City}."
Placeholders are defined by {
and }
, so this example has 5 placeholders: {Name}
, {Birthday:MMMM}
, {Age:000}
, {Age:year|years}
, and {Address.City}
.
Literal text is the area in-between placeholders: The user
, was born in
, , is
,
, old, and lives in
.
Each placeholder starts with a list of Selectors, such as Name
and Birthday
.
Selectors are separated by a period .
, known as an Operator, such as Address
.City
.
Selectors determine what data will be used in the output.
If the placeholder contains a colon :
, the remaining text is known as the Item Format.
For example, MMMM
, 000
, and year|years
are Item Formats.
Note that there is a distinction between the entire Format String and the placeholder's Item Format.
The Item Format determines how that data will be formatted. For example, MMMM
tells the DateTime to output the name of the Month, like January
. 000
tells an integer to use 3 digits. Please see Microsoft's Formatting Types Reference for complete documentation of Item Formats.
- Syntax, Terminology
- Placeholders and Nesting
- string.Format Compatibility
- Character Literals in Format Strings
- HTML With CSS or JavaScript
- Data Source Extensions
- Default _ DefaultFormatter
- Lists _ ListFormatter
- Choose _ ChooseFormatter
- Condition _ ConditionalFormatter
- Null _ NullFormatter
- SubString _ SubStringFormatter
- RegEx _ IsMatchFormatter
- Pluralization _ PluralLocalizationFormatter
- Localization _ LocalizationFormatter
- Templates _ TemplateFormatter
- TimeSpan _ TimeFormatter
- XML _ XElementFormatter
- Extension Methods
- Home
- Common Pitfalls
- HTML with CSS or JavaScript
- Overview
- Main Features
- Formatters
- Extra Features
- Console and StringBuilder
- TemplateFormatter
- SmartSettings to control Smart.Format behavior
- Additional Info
- License