From 453c2a4f37bdf6b061f54a075e7ff4b80d805fe8 Mon Sep 17 00:00:00 2001 From: Malfurious Date: Sat, 28 Oct 2023 08:02:18 -0400 Subject: dmt: Add server-side templating functionality This file is taken from the "werc" web "anti-framework" project, which is made available as Public Domain as well as MIT code. It is an awk script that implements a simple templating markup syntax. When run on an input file, it translates the content into equivalent shell syntax which can then be executed to produce the desired result. Therefore, the script should be invoked as `template.awk FILE | bash`, and the output can be streamed to the client. An overview of the template syntax follows: Lines beginning with '%' (no leading whitespace allowed) are taken as shell commands. Inline %{ ... %} gives the inner content taken as a shell command. Inline %( ... %) gives the inner content taken as a shell expression (which is substituted). All other text is echoed as-is. Signed-off-by: Malfurious --- dmt/template.awk | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100755 dmt/template.awk diff --git a/dmt/template.awk b/dmt/template.awk new file mode 100755 index 0000000..4274484 --- /dev/null +++ b/dmt/template.awk @@ -0,0 +1,55 @@ +#!/usr/bin/awk -f +function pr(str) { + if(lastc !~ "[{(]") + gsub(/'/, "''", str) + printf "%s", str +} +function trans(c) { + printf "%s", end + + lastc = c + end = "\n" + if(c == "%") + end = "" + else if(c == "(") + printf "echo -n " + else if(c ~ "[})]") { + end = "'\n" + printf "echo -n '" + } +} + +BEGIN { + lastc = "{" + trans("}") +} +END { + print end +} + +/^%/ && $0 !~ /^%[{()}%]/ && lastc !~ /[({]/ { + trans("%") + print substr($0, 2) + next +} +{ + if(lastc == "%") + trans("}") + n = split($0, a, "%") + pr(a[1]) + for(i=2; i<=n; i++) { + c = substr(a[i], 1, 1) + rest = substr(a[i], 2) + + if((lastc !~ "[({]" && c ~ "[({]") || + (lastc == "{" && c == "}") || + (lastc == "(" && c == ")")) + trans(c) + else if(c == "%") + pr("%") + else + pr("%" c) + pr(rest) + } + pr("\n") +} -- cgit v1.2.3