http.sh/src/template.sh

35 lines
884 B
Bash
Raw Normal View History

2021-02-28 03:33:58 +01:00
#!/bin/bash
# template.sh - basic templating engine
# render(array, template_file)
function render() {
local template="$(cat "$2")"
local -n ref=$1
local tmp=$(mktemp)
2021-02-28 03:33:58 +01:00
for key in ${!ref[@]}; do
if [[ "${ref[$key]}" != "" ]]; then
local value="$(html_encode "${ref[$key]}" | sed -E 's/\&/<2F>UwU<77>/g')"
echo 's/\{\{\.'"$key"'\}\}/'"$value"'/g' >> "$tmp"
else
echo 's/\{\{\.'"$key"'\}\}//g' >> "$tmp"
fi
2021-02-28 03:33:58 +01:00
done
template="$(sed -E -f "$tmp" <<< "$template")"
2021-02-28 03:33:58 +01:00
sed -E 's/<2F>UwU<77>/\&/g' <<< "$template"
rm "$tmp"
2021-02-28 03:33:58 +01:00
}
# render_unsafe(array, template_file)
function render_unsafe() {
local template="$(cat "$2")"
local -n ref=$1
local tmp=$(mktemp)
for key in ${!ref[@]}; do
2021-02-28 13:45:29 +01:00
local value="$(xxd -ps <<< "${ref[$key]}" | tr -d '\n' | sed -E 's/.{2}/\\x&/g')"
echo 's/\{\{\.'"$key"'\}\}/'"$value"'/g' >> "$tmp"
done
sed -E -f "$tmp" <<< "$template"
rm "$tmp"
}