' Template engine: replace placeholders like {{name}} in text
#COMPILE EXE
#DIM ALL

FUNCTION ReplaceAll(BYVAL text AS STRING, BYVAL find AS STRING, BYVAL replace AS STRING) AS STRING
    LOCAL pos AS LONG
    LOCAL result AS STRING
    result = text
    pos = INSTR(result, find)
    DO WHILE pos > 0
        result = LEFT$(result, pos - 1) + replace + MID$(result, pos + LEN(find))
        pos = INSTR(pos + LEN(replace), result, find)
    LOOP
    FUNCTION = result
END FUNCTION

FUNCTION TemplateSimple(BYVAL template AS STRING, BYVAL name AS STRING, BYVAL value AS STRING) AS STRING
    FUNCTION = ReplaceAll(template, "{{" + name + "}}", value)
END FUNCTION

FUNCTION TemplateMulti(BYVAL template AS STRING, n1 AS STRING, v1 AS STRING, n2 AS STRING, v2 AS STRING, n3 AS STRING, v3 AS STRING) AS STRING
    LOCAL result AS STRING
    result = template
    result = ReplaceAll(result, "{{" + n1 + "}}", v1)
    result = ReplaceAll(result, "{{" + n2 + "}}", v2)
    result = ReplaceAll(result, "{{" + n3 + "}}", v3)
    FUNCTION = result
END FUNCTION

FUNCTION PBMAIN() AS LONG
    LOCAL tmpl  AS STRING
    LOCAL result  AS STRING
    PRINT "=== Template Engine ==="
    PRINT
    tmpl = "Hello {{name}}, your order #{{id}} is {{status}}."
    PRINT "Template: " + tmpl
    PRINT
    result = TemplateMulti(tmpl, "name", "Alice", "id", "PBXB-001", "status", "shipped")
    PRINT "Result: " + result
    PRINT
    tmpl = "Dear {{title}} {{lastname}},..."
    tmpl = tmpl + " Your {{product}} has been {{action}}."
    tmpl = tmpl + " Tracking: {{tracking}}. Thank you, {{company}}"
    PRINT "Template: " + tmpl
    PRINT
    result = TemplateMulti(tmpl, "title", "Mr.", "lastname", "Johnson", "product", "Widget")
    result = ReplaceAll(result, "{{action}}", "delivered")
    result = ReplaceAll(result, "{{tracking}}", "1Z999AA10123456784")
    result = ReplaceAll(result, "{{company}}", "PBXB64 Corp")
    PRINT "Rendered: " + result
    PRINT
    result = TemplateSimple("Hello {{who}}!", "who", "World")
    PRINT "Simple: " + result
    result = TemplateSimple("{{a}} + {{b}} = {{c}}", "a", "2")
    PRINT "Partial: " + result
    PRINT
    PRINT "Template engine tests complete."
    FUNCTION = 0
END FUNCTION
