Text Templates in TypeScript

TypeScript provides several ways to work with templates and dynamic content. While it doesn’t have a built-in templating system like Go’s text/template, we can use string interpolation or third-party libraries for similar functionality. This example will demonstrate both approaches.

First, let’s look at using string interpolation:

function main() {
    // We can use template literals (backticks) for simple string interpolation
    const t1 = (value: any) => `Value is ${value}\n`;

    console.log(t1("some text"));
    console.log(t1(5));
    console.log(t1(["TypeScript", "JavaScript", "Python", "Ruby"]));

    // For objects, we can directly access properties
    const t2 = (obj: { Name: string }) => `Name: ${obj.Name}\n`;

    console.log(t2({ Name: "Jane Doe" }));

    // The same applies to maps (objects in TypeScript)
    console.log(t2({ Name: "Mickey Mouse" }));

    // Conditional rendering can be done with ternary operators
    const t3 = (value: any) => `${value ? "yes" : "no"}\n`;

    console.log(t3("not empty"));
    console.log(t3(""));

    // For loops can be used for ranging over arrays
    const t4 = (arr: string[]) => `Range: ${arr.join(" ")}\n`;

    console.log(t4(["TypeScript", "JavaScript", "Python", "Ruby"]));
}

main();

For more complex templating needs, you might want to use a third-party library like Handlebars. Here’s an example using Handlebars:

import Handlebars from 'handlebars';

function main() {
    // Create and compile a template
    const t1 = Handlebars.compile("Value is {{.}}\n");

    console.log(t1("some text"));
    console.log(t1(5));
    console.log(t1(["TypeScript", "JavaScript", "Python", "Ruby"]));

    // Template for objects
    const t2 = Handlebars.compile("Name: {{Name}}\n");

    console.log(t2({ Name: "Jane Doe" }));
    console.log(t2({ Name: "Mickey Mouse" }));

    // Conditional template
    const t3 = Handlebars.compile("{{#if .}}yes{{else}}no{{/if}}\n");

    console.log(t3("not empty"));
    console.log(t3(""));

    // Template for arrays
    const t4 = Handlebars.compile("Range: {{#each .}}{{this}} {{/each}}\n");

    console.log(t4(["TypeScript", "JavaScript", "Python", "Ruby"]));
}

main();

To run this TypeScript code, you’ll need to set up a TypeScript environment and install the Handlebars library. Here are the steps:

  1. Initialize a new Node.js project:

    $ npm init -y
  2. Install TypeScript and Handlebars:

    $ npm install typescript @types/node handlebars @types/handlebars
  3. Compile the TypeScript code:

    $ npx tsc your-file-name.ts
  4. Run the compiled JavaScript:

    $ node your-file-name.js

This example demonstrates how to achieve similar templating functionality in TypeScript as shown in the original example. The string interpolation method is more native to TypeScript, while the Handlebars approach provides a more powerful templating system for complex scenarios.