Text Templates in JavaScript

JavaScript doesn’t have a built-in templating engine like Go’s text/template. However, we can use a popular library called Handlebars.js to achieve similar functionality. First, you’ll need to install Handlebars using npm:

npm install handlebars

Now, let’s look at how to use Handlebars for templating in JavaScript:

const Handlebars = require('handlebars');

function main() {
    // We can create a new template and compile its body from a string.
    // Templates are a mix of static text and "expressions" enclosed in
    // {{...}} that are used to dynamically insert content.
    let t1 = Handlebars.compile('Value is {{.}}\n');

    // By "executing" the template we generate its text with
    // specific values for its expressions.
    console.log(t1('some text'));
    console.log(t1(5));
    console.log(t1(['JavaScript', 'Python', 'Ruby', 'PHP']));

    // If the data is an object we can use the {{fieldName}} expression to access
    // its properties.
    let t2 = Handlebars.compile('Name: {{Name}}\n');

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

    // The same applies to objects (which are similar to Go's maps)
    console.log(t2({ Name: 'Mickey Mouse' }));

    // Handlebars provides helpers for conditional execution
    let t3 = Handlebars.compile('{{#if .}}yes{{else}}no{{/if}}\n');
    console.log(t3('not empty'));
    console.log(t3(''));

    // Handlebars also provides helpers for iterating over arrays
    let t4 = Handlebars.compile('Range: {{#each .}}{{this}} {{/each}}\n');
    console.log(t4(['JavaScript', 'Python', 'Ruby', 'PHP']));
}

main();

This script demonstrates the following concepts:

  1. Creating and compiling templates using Handlebars.
  2. Executing templates with different types of data.
  3. Accessing object properties in templates.
  4. Using conditional statements in templates.
  5. Iterating over arrays in templates.

To run this script, save it as templates.js and execute it using Node.js:

$ node templates.js
Value is some text
Value is 5
Value is JavaScript,Python,Ruby,PHP
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: JavaScript Python Ruby PHP 

Handlebars.js provides a powerful templating system that’s similar in many ways to Go’s text/template. It allows for dynamic content insertion, conditional rendering, and iteration over data structures. While the syntax is slightly different, the core concepts remain the same.

Remember that in a browser environment, you would typically include Handlebars via a script tag and use it to render templates on the client side. In a Node.js environment, as shown here, we use it for server-side templating.