Text Templates in Lua

-- Lua offers string interpolation and libraries like lustache for templating.
-- This example demonstrates both approaches.

-- Simple string interpolation
local function interpolate(template, data)
    return (template:gsub('($%b{})', function(w) return data[w:sub(3, -2)] or w end))
end

-- Using the lustache library for more complex templating
local lustache = require "lustache"

-- We can create a new template as a string.
-- Templates are a mix of static text and "actions" enclosed in
-- {{...}} that are used to dynamically insert content.
local t1 = "Value is {{.}}\n"

-- By "rendering" the template we generate its text with
-- specific values for its actions. The {{.}} action is
-- replaced by the value passed as a parameter to render.
print(lustache:render(t1, "some text"))
print(lustache:render(t1, 5))
print(lustache:render(t1, {"Go", "Rust", "C++", "C#"}))

-- If the data is a table we can use the {{fieldName}} action to access
-- its fields.
local t2 = "Name: {{name}}\n"

print(lustache:render(t2, {name = "Jane Doe"}))

-- The same applies to nested tables.
print(lustache:render(t2, {name = "Mickey Mouse"}))

-- Conditional execution in templates
local t3 = "{{#.}}yes{{/.}}{{^.}}no{{/.}}\n"
print(lustache:render(t3, "not empty"))
print(lustache:render(t3, ""))

-- Iteration through tables
local t4 = "Range: {{#.}}{{.}} {{/.}}\n"
print(lustache:render(t4, {"Go", "Rust", "C++", "C#"}))

This Lua code demonstrates text templating using both simple string interpolation and the Lustache library, which provides Mustache-like templating for Lua.

In Lua, we don’t have built-in templating like Go’s text/template package. Instead, we can use string interpolation for simple cases and external libraries like Lustache for more complex templating needs.

The interpolate function demonstrates a simple string interpolation technique using Lua’s powerful pattern matching capabilities.

For more complex templating, we use the Lustache library, which provides similar functionality to Go’s templating system. The syntax is slightly different ({{.}} becomes {{.}} for the current value, {{fieldName}} for accessing fields), but the concepts are similar.

Conditional execution and iteration are handled using Mustache syntax in Lustache ({{#.}} for truthy values, {{^.}} for falsy values, and {{#.}}...{{/.}} for iteration).

To run this program, you would need to install the Lustache library (e.g., using LuaRocks) and then run the script with Lua:

$ luarocks install lustache
$ lua templates.lua
Value is some text
Value is 5
Value is {"Go","Rust","C++","C#"}
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: Go Rust C++ C# 

This example demonstrates how to achieve similar templating functionality in Lua as the Go example, using a combination of built-in language features and external libraries.