Programming Search⌘K

Taskcore

Use a text template

Also called text template, template substitution, placeholder substitution, fill a template, string.Template, mail merge, $name placeholders, ${name}, safe_substitute, template engine, envsubst, mustache.

Fill a template that is data, not code: change $name and ${name} to values from a table and $$ to $, in one pass, with string.Template, a regular expression with a callback, or a small scanner.

Task

Fill a text template: a text with named places that a program changes to values. A template is data. It can come from a file, a database or a translator, so the program does not know it when it is compiled. This is the difference from String interpolation, where the placeholders are part of the source code.

The template syntax is the one of Python string.Template1:

  • "$$ is an escape; it is replaced with a single $."1
  • "$identifier names a substitution placeholder"1, and the name is the key of the value. The name starts with a letter or an underscore, and "The first non-identifier character after the $ character terminates this placeholder specification"1.
  • "${identifier} is equivalent to $identifier. It is required when valid identifier characters follow the placeholder but are not part of the placeholder"1, as in ${noun}ification.

The function substitute(template, names, values) returns the filled text. values[i] is the value of names[i].

Template Values Result
Hello, $name! name = Ada Hello, Ada!
${item}s cost $$${price} item = Apple, price = 3 Apples cost $3
$$name name = Ada $name

A placeholder with a name that is not in the table is an error. The function reads the template once, from left to right: a value is copied into the result and is not read again as a template.

Solutions

Language Solution
Python string.Template(template).substitute(mapping)
JavaScript, TypeScript template.replace(regex, callback)
Java Matcher.replaceAll(callback) with Matcher.quoteReplacement
C# Regex.Replace(template, pattern, evaluator)
Go regexp.Regexp.ReplaceAllStringFunc
Rust a scanner over the text, with find('$')
C a scanner that writes into a buffer
C++ a scanner over a std::string_view
Bash a loop with [[ =~ ]] and an associative array

The regular expression of the solutions is \$(?:(\$)|\{(NAME)\}|(NAME))?, where NAME is [A-Za-z_][A-Za-z0-9_]*. Group 1 is $$, group 2 is ${name} and group 3 is $name. If no group matches, the $ is not valid. The callback looks up the name and returns the value. Each match is replaced once, so a value with a $ stays as it is.

  • Python. substitute "Performs the template substitution, returning a new string"1. A missing name raises KeyError. safe_substitute is different: "if placeholders are missing from mapping and kwds, instead of raising a KeyError exception, the original placeholder will appear in the resulting string intact"1.
  • JavaScript. String.prototype.replace with a function calls it for each match, with the groups as arguments. The text that the function returns is used as it is.
  • TypeScript. The same as JavaScript, with types.
  • Java. Matcher.replaceAll with a function reads $ and \ in the text that the function returns, as group references. The solution must give the value to Matcher.quoteReplacement (see Pitfalls).
  • C#. Regex.Replace with a MatchEvaluator uses the returned text as it is.
  • Go. ReplaceAllStringFunc calls the function for each match, and uses the text as it is. The function cannot return an error, so the solution keeps the first error in a variable. The package text/template is a full template language, with the syntax {{.Name}}: "Templates are executed by applying them to a data structure"2. By default, a missing key prints <no value>. With the option "missingkey=error", "Execution stops immediately with an error"2.
  • Rust. The standard library has no regular expressions. The scanner finds the next $ with find, copies the text before it, and reads the placeholder.
  • C. The scanner looks up each name in the two arrays, and returns -1 for an error.
  • C++. The same scanner, with std::string_view and a std::unordered_map.
  • Bash. The shell itself expands $name: "The basic form of parameter expansion is ${parameter}, which substitutes the value of parameter"3. But eval on a template runs any command in it, so the solution does not use it. A loop takes the text before the first $ with a regular expression, and adds the value from an associative array.

The Python solution, with the errors:

from string import Template

t = Template("${item}s cost $$${price}")
print(t.substitute(item="Apple", price="3"))
print(t.substitute({"item": "Pear", "price": "$x"}))
print(Template("Hello, $name!").safe_substitute())
try:
    Template("Hello, $name!").substitute()
except KeyError as e:
    print("KeyError", e)
try:
    Template("Cost: $5").substitute()
except ValueError as e:
    print("ValueError", e)
Output
Apples cost $3
Pears cost $$x
Hello, $name!
KeyError 'name'
ValueError Invalid placeholder in string: line 1, col 7

The second line shows that a value is not a template: the $x in the value stays.

Edge cases

  • No placeholders. The template is the result.
  • Empty template. The result is empty.
  • The escape. $$name is $name: the first two characters make one $, and name is plain text.
  • A name followed by letters. ${n}th with n = 4 is 4th. Without braces, $nth is the name nth.
  • A name followed by punctuation. $a.$b is 1.2, because a dot ends a name.
  • A value with a $ or braces. $x and ${y} in a value is copied as it is.
  • An empty value. [$v] with v = an empty string is [].
  • A value that is not used. It is not an error.
  • An unknown name. An error, not an empty string: an empty string in a letter or a command is a silent bug.

Pitfalls

  • Two passes. A loop that replaces each name in turn, with replace on the whole text, reads the values again. If the first value has $b in it, the second pass changes it. One pass over the template does not have this problem.
  • The replacement string in Java. In replaceAll, $ in the replacement is a group reference:

This code runs but gives a wrong answer on purpose.

import java.util.regex.Matcher;

public class Main {
    public static void main(String[] args) {
        String template = "Total: $price";
        String value = "$5";
        System.out.println(template.replace("$price", value));
        try {
            System.out.println(template.replaceAll("\\$price", value));
        } catch (RuntimeException e) {
            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
        System.out.println(template.replaceAll("\\$price", Matcher.quoteReplacement(value)));
    }
}
Output
Total: $5
IndexOutOfBoundsException: No group 5
Total: $5

String.replace takes the text as it is. replaceAll and Matcher.appendReplacement need Matcher.quoteReplacement. In JavaScript, C# and Go, the text that a replacement function returns is used as it is.

  • Templates from users. A template that is code, such as a Python format string with attribute access or a shell string for eval, can read or run more than the values. Use a template language that only substitutes names, and do not give users templates in a language that can run code.
  • Escaping for the output. The values are copied as they are. For HTML, a value with < must be escaped. Handlebars does it by default: "Because it was originally designed to generate HTML, Handlebars escapes values returned by a {{expression}}"4.
  • A missing name that is not an error. Python safe_substitute, Go text/template without an option and many template engines keep the placeholder or print an empty value. Choose the error for data that must be complete.

Code

The build runs the native tests of each language in a pinned toolchain.

template.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-text-template/.

from string import Template


def substitute(template: str, names: list[str], values: list[str]) -> str:
    """Return template with $$ changed to $, and $name and ${name}
    changed to the value of name. An unknown name raises KeyError."""
    return Template(template).substitute(dict(zip(names, values)))


if __name__ == "__main__":
    print(substitute("Hello, $name!", ["name"], ["Ada"]))
test_template.py 31 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-text-template/.

import pytest

from template import substitute

CASES = [
    ("greeting", "Hello, $name!", ["name"], ["Ada"], "Hello, Ada!"),
    ("braces", "${item}s cost $$${price}", ["item", "price"], ["Apple", "3"], "Apples cost $3"),
    ("two-uses", "$a and $a again", ["a"], ["x"], "x and x again"),
    ("no-placeholders", "plain text", [], [], "plain text"),
    ("empty-template", "", ["x"], ["1"], ""),
    ("dollar-escape", "$$name", ["name"], ["Ada"], "$name"),
    ("adjacent-text", "${n}th", ["n"], ["4"], "4th"),
    ("value-with-dollar", "$v", ["v"], ["$x and ${y}"], "$x and ${y}"),
    ("empty-value", "[$v]", ["v"], [""], "[]"),
    ("underscore-name", "$first_name $last_name", ["first_name", "last_name"], ["Grace", "Hopper"], "Grace Hopper"),
    ("name-ends-at-punct", "$a.$b", ["a", "b"], ["1", "2"], "1.2"),
    ("unused-value", "$a", ["a", "b"], ["1", "2"], "1"),
]


@pytest.mark.parametrize(("name", "template", "names", "values", "want"), CASES, ids=[c[0] for c in CASES])
def test_substitute(name, template, names, values, want):
    assert substitute(template, names, values) == want


def test_unknown_name():
    with pytest.raises(KeyError):
        substitute("Hi $who", ["name"], ["Ada"])
template.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

#ifndef TEMPLATE_HPP
#define TEMPLATE_HPP

#include <cctype>
#include <cstddef>
#include <stdexcept>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>

// Returns tmpl with $$ changed to $, and $name and ${name} changed to the
// value of name. It reads the template once, so a value is not read as a
// template. An unknown name throws std::out_of_range, and a $ without a name
// throws std::invalid_argument.
inline std::string substitute(std::string_view tmpl, const std::vector<std::string>& names,
                              const std::vector<std::string>& values) {
    std::unordered_map<std::string_view, std::string_view> table;
    for (std::size_t i = 0; i < names.size(); ++i) {
        table[names[i]] = values[i];
    }
    auto is_name_char = [](char c) { return std::isalnum(static_cast<unsigned char>(c)) != 0 || c == '_'; };
    std::string out;
    std::size_t i = 0;
    while (i < tmpl.size()) {
        const std::size_t dollar = tmpl.find('$', i);
        if (dollar == std::string_view::npos) {
            out += tmpl.substr(i);
            break;
        }
        out += tmpl.substr(i, dollar - i);
        std::size_t p = dollar + 1;
        if (p < tmpl.size() && tmpl[p] == '$') {
            out += '$';
            i = p + 1;
            continue;
        }
        const bool braced = p < tmpl.size() && tmpl[p] == '{';
        const std::size_t start = braced ? p + 1 : p;
        std::size_t end = start;
        if (end < tmpl.size() && (std::isalpha(static_cast<unsigned char>(tmpl[end])) != 0 || tmpl[end] == '_')) {
            while (end < tmpl.size() && is_name_char(tmpl[end])) {
                ++end;
            }
        }
        if (end == start || (braced && (end >= tmpl.size() || tmpl[end] != '}'))) {
            throw std::invalid_argument("a $ without a name");
        }
        out += table.at(tmpl.substr(start, end - start));
        i = braced ? end + 1 : end;
    }
    return out;
}

#endif
test_template.cpp 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

#include <cstdio>
#include <stdexcept>
#include <string>
#include <vector>

#include "template.hpp"

namespace {

struct test_case {
    const char* name;
    const char* tmpl;
    std::vector<std::string> names;
    std::vector<std::string> values;
    const char* want;
};

const test_case cases[] = {
    {"greeting", "Hello, $name!", {"name"}, {"Ada"}, "Hello, Ada!"},
    {"braces", "${item}s cost $$${price}", {"item", "price"}, {"Apple", "3"}, "Apples cost $3"},
    {"two-uses", "$a and $a again", {"a"}, {"x"}, "x and x again"},
    {"no-placeholders", "plain text", {}, {}, "plain text"},
    {"empty-template", "", {"x"}, {"1"}, ""},
    {"dollar-escape", "$$name", {"name"}, {"Ada"}, "$name"},
    {"adjacent-text", "${n}th", {"n"}, {"4"}, "4th"},
    {"value-with-dollar", "$v", {"v"}, {"$x and ${y}"}, "$x and ${y}"},
    {"empty-value", "[$v]", {"v"}, {""}, "[]"},
    {"underscore-name", "$first_name $last_name", {"first_name", "last_name"}, {"Grace", "Hopper"}, "Grace Hopper"},
    {"name-ends-at-punct", "$a.$b", {"a", "b"}, {"1", "2"}, "1.2"},
    {"unused-value", "$a", {"a", "b"}, {"1", "2"}, "1"},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const std::string got = substitute(c.tmpl, c.names, c.values);
        if (got != c.want) {
            std::printf("FAIL %s: got \"%s\"\n", c.name, got.c_str());
            ++failures;
        }
    }
    try {
        substitute("Hi $who", {"name"}, {"Ada"});
        std::printf("FAIL unknown name\n");
        ++failures;
    } catch (const std::out_of_range&) {
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Template.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** A text template with $name, ${name} and $$, as in Python string.Template. */
public final class Template {
    private static final Pattern PLACEHOLDER =
            Pattern.compile("\\$(?:(\\$)|\\{([A-Za-z_][A-Za-z0-9_]*)\\}|([A-Za-z_][A-Za-z0-9_]*))?");

    private Template() {}

    /**
     * Returns template with $$ changed to $, and $name and ${name} changed to
     * the value of name. replaceAll reads $ and \ in the returned text, so each
     * value goes through Matcher.quoteReplacement. An unknown name or a $
     * without a name throws IllegalArgumentException.
     */
    public static String substitute(String template, String[] names, String[] values) {
        Map<String, String> table = new HashMap<>();
        for (int i = 0; i < names.length; i++) {
            table.put(names[i], values[i]);
        }
        return PLACEHOLDER.matcher(template).replaceAll(m -> {
            if (m.group(1) != null) {
                return Matcher.quoteReplacement("$");
            }
            String name = m.group(2) != null ? m.group(2) : m.group(3);
            if (name == null) {
                throw new IllegalArgumentException("a $ without a name at " + m.start());
            }
            String value = table.get(name);
            if (value == null) {
                throw new IllegalArgumentException("unknown name: " + name);
            }
            return Matcher.quoteReplacement(value);
        });
    }

    public static void main(String[] args) {
        System.out.println(substitute("Hello, $name!", new String[] {"name"}, new String[] {"Ada"}));
    }
}
TemplateTest.java 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class TemplateTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("greeting", "Hello, $name!", new String[]{"name"}, new String[]{"Ada"}, "Hello, Ada!"),
                Arguments.of("braces", "${item}s cost $$${price}", new String[]{"item", "price"}, new String[]{"Apple", "3"}, "Apples cost $3"),
                Arguments.of("two-uses", "$a and $a again", new String[]{"a"}, new String[]{"x"}, "x and x again"),
                Arguments.of("no-placeholders", "plain text", new String[]{}, new String[]{}, "plain text"),
                Arguments.of("empty-template", "", new String[]{"x"}, new String[]{"1"}, ""),
                Arguments.of("dollar-escape", "$$name", new String[]{"name"}, new String[]{"Ada"}, "$name"),
                Arguments.of("adjacent-text", "${n}th", new String[]{"n"}, new String[]{"4"}, "4th"),
                Arguments.of("value-with-dollar", "$v", new String[]{"v"}, new String[]{"$x and ${y}"}, "$x and ${y}"),
                Arguments.of("empty-value", "[$v]", new String[]{"v"}, new String[]{""}, "[]"),
                Arguments.of("underscore-name", "$first_name $last_name", new String[]{"first_name", "last_name"}, new String[]{"Grace", "Hopper"}, "Grace Hopper"),
                Arguments.of("name-ends-at-punct", "$a.$b", new String[]{"a", "b"}, new String[]{"1", "2"}, "1.2"),
                Arguments.of("unused-value", "$a", new String[]{"a", "b"}, new String[]{"1", "2"}, "1")
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void substitute(String name, String template, String[] names, String[] values, String want) {
        assertEquals(want, Template.substitute(template, names, values));
    }

    @Test
    void unknownName() {
        assertThrows(IllegalArgumentException.class,
                () -> Template.substitute("Hi $who", new String[] {"name"}, new String[] {"Ada"}));
    }
}
template.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

#include "template.h"

#include <ctype.h>
#include <string.h>

// put copies n bytes of s to out at *len, as far as size allows, and adds n to *len.
static void put(char *out, size_t size, size_t *len, const char *s, size_t n) {
    for (size_t i = 0; i < n; i++, (*len)++) {
        if (*len + 1 < size) {
            out[*len] = s[i];
        }
    }
}

static size_t name_length(const char *s) {
    size_t n = 0;
    if (isalpha((unsigned char)s[0]) || s[0] == '_') {
        n = 1;
        while (isalnum((unsigned char)s[n]) || s[n] == '_') {
            n++;
        }
    }
    return n;
}

int substitute(char *out, size_t size, const char *template, const char *const names[],
               const char *const values[], size_t count) {
    size_t len = 0;
    const char *p = template;
    for (;;) {
        const char *dollar = strchr(p, '$');
        if (dollar == NULL) {
            put(out, size, &len, p, strlen(p));
            break;
        }
        put(out, size, &len, p, (size_t)(dollar - p));
        p = dollar + 1;
        if (*p == '$') {
            put(out, size, &len, "$", 1);
            p++;
            continue;
        }
        int braced = *p == '{';
        const char *name = braced ? p + 1 : p;
        size_t n = name_length(name);
        if (n == 0 || (braced && name[n] != '}')) {
            return -1;
        }
        size_t i = 0;
        while (i < count && (strlen(names[i]) != n || strncmp(names[i], name, n) != 0)) {
            i++;
        }
        if (i == count) {
            return -1;
        }
        put(out, size, &len, values[i], strlen(values[i]));
        p = name + n + (braced ? 1 : 0);
    }
    if (size > 0) {
        out[len < size ? len : size - 1] = '\0';
    }
    return (int)len;
}
template.h 17 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

#ifndef TEMPLATE_H
#define TEMPLATE_H

#include <stddef.h>

// Writes template into out with $$ changed to $, and $name and ${name}
// changed to values[i] where names[i] is name. count is the length of names
// and values. Returns the length of the full result, as snprintf does: if it
// is size or more, the result was cut to fit. Returns -1 for an unknown name
// or a $ without a name.
int substitute(char *out, size_t size, const char *template, const char *const names[],
               const char *const values[], size_t count);

#endif
test_template.c 61 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

#include "template.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct test_case {
    const char *name;
    const char *template;
    const char *names[4];
    const char *values[4];
    size_t count;
    const char *want;
};

static const struct test_case cases[] = {
    {"greeting", "Hello, $name!", {"name"}, {"Ada"}, 1, "Hello, Ada!"},
    {"braces", "${item}s cost $$${price}", {"item", "price"}, {"Apple", "3"}, 2, "Apples cost $3"},
    {"two-uses", "$a and $a again", {"a"}, {"x"}, 1, "x and x again"},
    {"no-placeholders", "plain text", {}, {}, 0, "plain text"},
    {"empty-template", "", {"x"}, {"1"}, 1, ""},
    {"dollar-escape", "$$name", {"name"}, {"Ada"}, 1, "$name"},
    {"adjacent-text", "${n}th", {"n"}, {"4"}, 1, "4th"},
    {"value-with-dollar", "$v", {"v"}, {"$x and ${y}"}, 1, "$x and ${y}"},
    {"empty-value", "[$v]", {"v"}, {""}, 1, "[]"},
    {"underscore-name", "$first_name $last_name", {"first_name", "last_name"}, {"Grace", "Hopper"}, 2, "Grace Hopper"},
    {"name-ends-at-punct", "$a.$b", {"a", "b"}, {"1", "2"}, 2, "1.2"},
    {"unused-value", "$a", {"a", "b"}, {"1", "2"}, 2, "1"},
};

int main(void) {
    int failures = 0;
    char buf[64];
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        int n = substitute(buf, sizeof buf, c->template, c->names, c->values, c->count);
        if (n != (int)strlen(c->want) || strcmp(buf, c->want) != 0) {
            printf("FAIL %s: got %d \"%s\"\n", c->name, n, buf);
            failures++;
        }
    }
    const char *const names[] = {"name"};
    const char *const values[] = {"Ada"};
    if (substitute(buf, sizeof buf, "Hi $who", names, values, 1) != -1) {
        printf("FAIL unknown name\n");
        failures++;
    }
    char small[6];
    if (substitute(small, sizeof small, "Hello, $name!", names, values, 1) != 11 || strcmp(small, "Hello") != 0) {
        printf("FAIL small buffer\n");
        failures++;
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
TextTemplate.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

/// <summary>A text template with $name, ${name} and $$, as in Python string.Template.</summary>
public static class TextTemplate
{
    private static readonly Regex Placeholder =
        new(@"\$(?:(\$)|\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))?");

    /// <summary>
    /// Returns template with $$ changed to $, and $name and ${name} changed
    /// to the value of name. The text that the evaluator returns is used as it
    /// is. An unknown name throws KeyNotFoundException, and a $ without a
    /// name throws FormatException.
    /// </summary>
    public static string Substitute(string template, string[] names, string[] values)
    {
        var table = new Dictionary<string, string>();
        for (var i = 0; i < names.Length; i++)
        {
            table[names[i]] = values[i];
        }
        return Placeholder.Replace(template, m =>
        {
            if (m.Groups[1].Success)
            {
                return "$";
            }
            var group = m.Groups[2].Success ? m.Groups[2] : m.Groups[3];
            if (!group.Success)
            {
                throw new FormatException($"a $ without a name at {m.Index}");
            }
            return table.TryGetValue(group.Value, out var value)
                ? value
                : throw new KeyNotFoundException($"unknown name: {group.Value}");
        });
    }
}
TextTemplateTests.cs 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

using System;
using System.Collections.Generic;
using Xunit;

public sealed class TextTemplateTests
{
    public static TheoryData<string, string, string[], string[], string> Cases => new()
    {
        { "greeting", "Hello, $name!", new string[] { "name" }, new string[] { "Ada" }, "Hello, Ada!" },
        { "braces", "${item}s cost $$${price}", new string[] { "item", "price" }, new string[] { "Apple", "3" }, "Apples cost $3" },
        { "two-uses", "$a and $a again", new string[] { "a" }, new string[] { "x" }, "x and x again" },
        { "no-placeholders", "plain text", Array.Empty<string>(), Array.Empty<string>(), "plain text" },
        { "empty-template", "", new string[] { "x" }, new string[] { "1" }, "" },
        { "dollar-escape", "$$name", new string[] { "name" }, new string[] { "Ada" }, "$name" },
        { "adjacent-text", "${n}th", new string[] { "n" }, new string[] { "4" }, "4th" },
        { "value-with-dollar", "$v", new string[] { "v" }, new string[] { "$x and ${y}" }, "$x and ${y}" },
        { "empty-value", "[$v]", new string[] { "v" }, new string[] { "" }, "[]" },
        { "underscore-name", "$first_name $last_name", new string[] { "first_name", "last_name" }, new string[] { "Grace", "Hopper" }, "Grace Hopper" },
        { "name-ends-at-punct", "$a.$b", new string[] { "a", "b" }, new string[] { "1", "2" }, "1.2" },
        { "unused-value", "$a", new string[] { "a", "b" }, new string[] { "1", "2" }, "1" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Substitute(string name, string template, string[] names, string[] values, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, TextTemplate.Substitute(template, names, values));
    }

    [Fact]
    public void UnknownName()
    {
        Assert.Throws<KeyNotFoundException>(() => TextTemplate.Substitute("Hi $who", new[] { "name" }, new[] { "Ada" }));
    }
}
template.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

const PLACEHOLDER = /\$(?:(\$)|\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))?/g;

/**
 * Returns template with $$ changed to $, and $name and ${name} changed to
 * the value of name. It reads the template once, so a value is not read as a
 * template. An unknown name or a $ without a name throws an Error.
 */
export function substitute(template, names, values) {
  const table = new Map(names.map((n, i) => [n, values[i]]));
  return template.replace(PLACEHOLDER, (_match, dollar, braced, bare, offset) => {
    if (dollar !== undefined) {
      return "$";
    }
    const name = braced ?? bare;
    if (name === undefined) {
      throw new Error(`a $ without a name at ${offset}`);
    }
    const value = table.get(name);
    if (value === undefined) {
      throw new Error(`unknown name: ${name}`);
    }
    return value;
  });
}
template.test.js 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { substitute } from "./template.js";

const cases = [
  ["greeting", "Hello, $name!", ["name"], ["Ada"], "Hello, Ada!"],
  ["braces", "${item}s cost $$${price}", ["item", "price"], ["Apple", "3"], "Apples cost $3"],
  ["two-uses", "$a and $a again", ["a"], ["x"], "x and x again"],
  ["no-placeholders", "plain text", [], [], "plain text"],
  ["empty-template", "", ["x"], ["1"], ""],
  ["dollar-escape", "$$name", ["name"], ["Ada"], "$name"],
  ["adjacent-text", "${n}th", ["n"], ["4"], "4th"],
  ["value-with-dollar", "$v", ["v"], ["$x and ${y}"], "$x and ${y}"],
  ["empty-value", "[$v]", ["v"], [""], "[]"],
  ["underscore-name", "$first_name $last_name", ["first_name", "last_name"], ["Grace", "Hopper"], "Grace Hopper"],
  ["name-ends-at-punct", "$a.$b", ["a", "b"], ["1", "2"], "1.2"],
  ["unused-value", "$a", ["a", "b"], ["1", "2"], "1"],
];

for (const [name, template, names, values, want] of cases) {
  test(name, () => {
    assert.equal(substitute(template, names, values), want);
  });
}

test("unknown-name", () => {
  assert.throws(() => substitute("Hi $who", ["name"], ["Ada"]), /unknown name: who/);
});
template.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

const PLACEHOLDER = /\$(?:(\$)|\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))?/g;

/**
 * Returns template with $$ changed to $, and $name and ${name} changed to
 * the value of name. It reads the template once, so a value is not read as a
 * template. An unknown name or a $ without a name throws an Error.
 */
export function substitute(template: string, names: string[], values: string[]): string {
  const table = new Map(names.map((n, i) => [n, values[i]]));
  return template.replace(PLACEHOLDER, (_match: string, dollar?: string, braced?: string, bare?: string, offset?: number) => {
    if (dollar !== undefined) {
      return "$";
    }
    const name = braced ?? bare;
    if (name === undefined) {
      throw new Error(`a $ without a name at ${offset}`);
    }
    const value = table.get(name);
    if (value === undefined) {
      throw new Error(`unknown name: ${name}`);
    }
    return value;
  });
}
template.test.ts 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { substitute } from "./template.ts";

const cases: [string, string, string[], string[], string][] = [
  ["greeting", "Hello, $name!", ["name"], ["Ada"], "Hello, Ada!"],
  ["braces", "${item}s cost $$${price}", ["item", "price"], ["Apple", "3"], "Apples cost $3"],
  ["two-uses", "$a and $a again", ["a"], ["x"], "x and x again"],
  ["no-placeholders", "plain text", [], [], "plain text"],
  ["empty-template", "", ["x"], ["1"], ""],
  ["dollar-escape", "$$name", ["name"], ["Ada"], "$name"],
  ["adjacent-text", "${n}th", ["n"], ["4"], "4th"],
  ["value-with-dollar", "$v", ["v"], ["$x and ${y}"], "$x and ${y}"],
  ["empty-value", "[$v]", ["v"], [""], "[]"],
  ["underscore-name", "$first_name $last_name", ["first_name", "last_name"], ["Grace", "Hopper"], "Grace Hopper"],
  ["name-ends-at-punct", "$a.$b", ["a", "b"], ["1", "2"], "1.2"],
  ["unused-value", "$a", ["a", "b"], ["1", "2"], "1"],
];

for (const [name, template, names, values, want] of cases) {
  test(name, () => {
    assert.equal(substitute(template, names, values), want);
  });
}

test("unknown-name", () => {
  assert.throws(() => substitute("Hi $who", ["name"], ["Ada"]), /unknown name: who/);
});
template.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

// Package template fills a text template with $name, ${name} and $$, as in
// Python string.Template.
package template

import (
	"fmt"
	"regexp"
)

var placeholder = regexp.MustCompile(`\$(?:(\$)|\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))?`)

// Substitute returns template with $$ changed to $, and $name and ${name}
// changed to the value of name. The text that the function returns is used
// as it is, so a value is not read as a template. An unknown name or a $
// without a name is an error.
func Substitute(template string, names, values []string) (string, error) {
	table := make(map[string]string, len(names))
	for i, n := range names {
		table[n] = values[i]
	}
	var err error
	out := placeholder.ReplaceAllStringFunc(template, func(m string) string {
		g := placeholder.FindStringSubmatch(m)
		name := g[2] + g[3]
		switch {
		case g[1] != "":
			return "$"
		case name == "":
			if err == nil {
				err = fmt.Errorf("a $ without a name")
			}
			return m
		}
		v, ok := table[name]
		if !ok && err == nil {
			err = fmt.Errorf("unknown name: %s", name)
		}
		return v
	})
	if err != nil {
		return "", err
	}
	return out, nil
}
template_test.go 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

package template

import "testing"

var cases = []struct {
	name     string
	template string
	names    []string
	values   []string
	want     string
}{
	{"greeting", "Hello, $name!", []string{"name"}, []string{"Ada"}, "Hello, Ada!"},
	{"braces", "${item}s cost $$${price}", []string{"item", "price"}, []string{"Apple", "3"}, "Apples cost $3"},
	{"two-uses", "$a and $a again", []string{"a"}, []string{"x"}, "x and x again"},
	{"no-placeholders", "plain text", []string{}, []string{}, "plain text"},
	{"empty-template", "", []string{"x"}, []string{"1"}, ""},
	{"dollar-escape", "$$name", []string{"name"}, []string{"Ada"}, "$name"},
	{"adjacent-text", "${n}th", []string{"n"}, []string{"4"}, "4th"},
	{"value-with-dollar", "$v", []string{"v"}, []string{"$x and ${y}"}, "$x and ${y}"},
	{"empty-value", "[$v]", []string{"v"}, []string{""}, "[]"},
	{"underscore-name", "$first_name $last_name", []string{"first_name", "last_name"}, []string{"Grace", "Hopper"}, "Grace Hopper"},
	{"name-ends-at-punct", "$a.$b", []string{"a", "b"}, []string{"1", "2"}, "1.2"},
	{"unused-value", "$a", []string{"a", "b"}, []string{"1", "2"}, "1"},
}

func TestSubstitute(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got, err := Substitute(c.template, c.names, c.values)
			if err != nil || got != c.want {
				t.Fatalf("Substitute(%q) = %q, %v, want %q", c.template, got, err, c.want)
			}
		})
	}
}

func TestUnknownName(t *testing.T) {
	if _, err := Substitute("Hi $who", []string{"name"}, []string{"Ada"}); err == nil {
		t.Fatal("want an error for an unknown name")
	}
}
template.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

fn is_name(s: &str) -> bool {
    let mut chars = s.chars();
    matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// Returns template with $$ changed to $, and $name and ${name} changed to
/// the value of name. It reads the template once, so a value is not read as
/// a template. An unknown name or a $ without a name is an error.
pub fn substitute(template: &str, names: &[&str], values: &[&str]) -> Result<String, String> {
    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    while let Some(i) = rest.find('$') {
        out.push_str(&rest[..i]);
        let after = &rest[i + 1..];
        if let Some(r) = after.strip_prefix('$') {
            out.push('$');
            rest = r;
            continue;
        }
        let (name, next) = if let Some(r) = after.strip_prefix('{') {
            let end = r.find('}').ok_or("a ${ without a }")?;
            (&r[..end], &r[end + 1..])
        } else {
            let end = after
                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
                .unwrap_or(after.len());
            (&after[..end], &after[end..])
        };
        if !is_name(name) {
            return Err(format!("a $ without a name: {rest}"));
        }
        let k = names
            .iter()
            .position(|n| *n == name)
            .ok_or_else(|| format!("unknown name: {name}"))?;
        out.push_str(values[k]);
        rest = next;
    }
    out.push_str(rest);
    Ok(out)
}
tests/template_test.rs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-text-template/.

use algo_use_a_text_template::substitute;

const CASES: &[(&str, &str, &[&str], &[&str], &str)] = &[
    ("greeting", "Hello, $name!", &["name"], &["Ada"], "Hello, Ada!"),
    ("braces", "${item}s cost $$${price}", &["item", "price"], &["Apple", "3"], "Apples cost $3"),
    ("two-uses", "$a and $a again", &["a"], &["x"], "x and x again"),
    ("no-placeholders", "plain text", &[], &[], "plain text"),
    ("empty-template", "", &["x"], &["1"], ""),
    ("dollar-escape", "$$name", &["name"], &["Ada"], "$name"),
    ("adjacent-text", "${n}th", &["n"], &["4"], "4th"),
    ("value-with-dollar", "$v", &["v"], &["$x and ${y}"], "$x and ${y}"),
    ("empty-value", "[$v]", &["v"], &[""], "[]"),
    ("underscore-name", "$first_name $last_name", &["first_name", "last_name"], &["Grace", "Hopper"], "Grace Hopper"),
    ("name-ends-at-punct", "$a.$b", &["a", "b"], &["1", "2"], "1.2"),
    ("unused-value", "$a", &["a", "b"], &["1", "2"], "1"),
];

#[test]
fn cases() {
    for &(name, template, names, values, want) in CASES {
        assert_eq!(substitute(template, names, values).as_deref(), Ok(want), "{name}");
    }
}

#[test]
fn unknown_name() {
    assert!(substitute("Hi $who", &["name"], &["Ada"]).is_err());
}
template.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-text-template/.

# substitute template [name value]...: print template with $$ changed to $,
# and $name and ${name} changed to the value of name. Each pass of the loop
# takes the text before the first $ and one placeholder, so a value is not
# read as a template. It does not use eval, which would run the commands in
# a template. An unknown name or a $ without a name returns 1.
substitute() {
  local rest=$1 out='' name
  shift
  local -A table=()
  while (($# >= 2)); do
    table[$1]=$2
    shift 2
  done
  local re='^([^$]*)\$(\$|\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))(.*)$'
  while [[ $rest == *'$'* ]]; do
    if ! [[ $rest =~ $re ]]; then
      printf 'a $ without a name\n' >&2
      return 1
    fi
    out+=${BASH_REMATCH[1]}
    name=${BASH_REMATCH[3]}${BASH_REMATCH[4]}
    rest=${BASH_REMATCH[5]}
    if [[ ${BASH_REMATCH[2]} == '$' ]]; then
      out+='$'
    elif [[ -v table[$name] ]]; then
      out+=${table[$name]}
    else
      printf 'unknown name: %s\n' "$name" >&2
      return 1
    fi
  done
  printf '%s\n' "$out$rest"
}
test_template.bats 84 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-text-template/.

setup() {
  source "$BATS_TEST_DIRNAME/template.sh"
}

@test "greeting" {
  run substitute 'Hello, $name!' 'name' 'Ada'
  [ "$status" -eq 0 ]
  [ "$output" = 'Hello, Ada!' ]
}

@test "braces" {
  run substitute '${item}s cost $$${price}' 'item' 'Apple' 'price' '3'
  [ "$status" -eq 0 ]
  [ "$output" = 'Apples cost $3' ]
}

@test "two-uses" {
  run substitute '$a and $a again' 'a' 'x'
  [ "$status" -eq 0 ]
  [ "$output" = 'x and x again' ]
}

@test "no-placeholders" {
  run substitute 'plain text' 
  [ "$status" -eq 0 ]
  [ "$output" = 'plain text' ]
}

@test "empty-template" {
  run substitute '' 'x' '1'
  [ "$status" -eq 0 ]
  [ "$output" = '' ]
}

@test "dollar-escape" {
  run substitute '$$name' 'name' 'Ada'
  [ "$status" -eq 0 ]
  [ "$output" = '$name' ]
}

@test "adjacent-text" {
  run substitute '${n}th' 'n' '4'
  [ "$status" -eq 0 ]
  [ "$output" = '4th' ]
}

@test "value-with-dollar" {
  run substitute '$v' 'v' '$x and ${y}'
  [ "$status" -eq 0 ]
  [ "$output" = '$x and ${y}' ]
}

@test "empty-value" {
  run substitute '[$v]' 'v' ''
  [ "$status" -eq 0 ]
  [ "$output" = '[]' ]
}

@test "underscore-name" {
  run substitute '$first_name $last_name' 'first_name' 'Grace' 'last_name' 'Hopper'
  [ "$status" -eq 0 ]
  [ "$output" = 'Grace Hopper' ]
}

@test "name-ends-at-punct" {
  run substitute '$a.$b' 'a' '1' 'b' '2'
  [ "$status" -eq 0 ]
  [ "$output" = '1.2' ]
}

@test "unused-value" {
  run substitute '$a' 'a' '1' 'b' '2'
  [ "$status" -eq 0 ]
  [ "$output" = '1' ]
}

@test "unknown-name" {
  run substitute 'Hi $who' name Ada
  [ "$status" -eq 1 ]
}

References

  1. string, Common string operations, Python documentation, Template strings ($-strings)
  2. Package text/template, The Go Standard Library, Overview; Template.Option
  3. Shell Parameter Expansion, Bash Reference Manual, 3.5.3
  4. Introduction, Handlebars, What is Handlebars; HTML escaping

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source