Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

Often you want formatted text, but you're not interested in writing it to Stdout or Stderr.

The existing CSharp Formatter tutorial doesn't make it obvious that string formatting is available in any other context than the console. But it is!! Anywhere you use strings, you can also create formatted strings!!

The interesting code is in the tango.text.convert.Layout module, in a templated class called Layout(T). You can instantiate the template with char, dchar, or wchar types, and use the OpCall syntax to format your strings, like this:

import tango.text.convert.Layout;

// ...

auto charFormatter = new Layout!(char);
char[] formattedString = charFormatter("This is the thing: '{}'", thing);

auto wcharFormatter = new Layout!(wchar);
wchar[] formattedWString = wcharFormatter ("This is the thing: '{}'", thing);

auto dcharFormatter = new Layout!(dchar);
dchar[] formattedDString = dcharFormatter ("This is the thing: '{}'", thing);

You might consider the sprint() method also, which avoids heap activity. Also, if you're already using Stdout or Stderr, it can be simpler to apply the Layout instance exposed there instead:

char[256] out = void;
auto content = Stdout.layout.sprint (out, "This is the thing: '{}'", thing);

One might also utilize the locale enabled extensions in a similar manner, by using tango.text.locale.Locale instead of Layout. Locale is a derivative of Layout, so all formatting methods are common with Locale adding support for more sophisticated formatting options along with culture-specific currency, time and date consideration:

import tango.text.locale.Locale;

auto layout = new Locale (Culture.getCulture ("fr-FR"));
auto formattedString = layout ("This is the date: {}", DateTime.now);

It's also possible to make Stdout and Stderr locale-aware, by replacing the (shared) layout instance:

Stdout.layout = new Locale (Culture.getCulture ("fr-FR"));