Text Templates in D Programming Language

The D programming language offers built-in support for creating dynamic content or showing customized output to the user with the std.format module. This module provides similar functionality to Go’s text/template package.

import std.stdio;
import std.format;
import std.array;

void main()
{
    // We can create a new format string and use it to format values.
    // Format strings in D use `%s` as a placeholder for values.
    string t1 = "Value is %s\n";
    writef(t1, "some text");
    writef(t1, 5);
    writef(t1, ["D", "Rust", "C++", "C#"]);

    // If the data is a struct we can use named format specifiers to access its fields.
    // The fields should be accessible when formatting.
    struct Person { string name; }
    string t2 = "Name: %s\n";
    writef(t2, Person("Jane Doe"));

    // The same applies to associative arrays (D's equivalent of maps).
    string[string] person = ["name": "Mickey Mouse"];
    writef(t2, person["name"]);

    // D doesn't have a direct equivalent to Go's template conditional execution,
    // but we can achieve similar results using regular D code.
    string t3(string value)
    {
        return value.length ? "yes\n" : "no\n";
    }
    write(t3("not empty"));
    write(t3(""));

    // For looping through arrays or other iterable types, we can use D's
    // standard looping constructs along with the join function.
    string[] languages = ["D", "Rust", "C++", "C#"];
    writeln("Range: ", languages.join(" "));
}

To run the program, save it as templates.d and use the D compiler (dmd) to compile and run:

$ dmd -run templates.d
Value is some text
Value is 5
Value is ["D", "Rust", "C++", "C#"]
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: D Rust C++ C#

This D code demonstrates similar functionality to the Go example, using D’s standard library functions for formatting and output. While D doesn’t have a built-in templating system like Go’s text/template, it provides powerful string formatting capabilities that can be used to achieve similar results.