specifications

Specification and standard documents
git clone git://git.finwo.net/misc/specifications
Log | Files | Refs | README | LICENSE

commit a13925a9fb469b0ca095535a4a67e5374dd831b6
parent 33f548fa7f713bd428f7a8f41c7a6a73788ce8d9
Author: finwo <finwo@pm.me>
Date:   Wed, 12 Aug 2020 11:36:53 +0200

Updated script/template.sh

Diffstat:
Mscript/template.sh | 35+++++++++++++++++++++++++++++++----
1 file changed, 31 insertions(+), 4 deletions(-)

diff --git a/script/template.sh b/script/template.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # Very simple templating system that replaces {{VAR}} by the value of $VAR. +# Supports default values by writting {{VAR=value}} in the template. # Replaces all {{VAR}} by the $VAR value in a template file and outputs it @@ -11,16 +12,19 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" usage=" Usage: ${PROGNAME} -h|--help - ${PROGNAME} [-c|--config config_file] template_file [...template_file] + ${PROGNAME} [-c|--config config_file] [-p|--partials partials_dir] template_file [...template_file] Options: - -h --help Show this help text - -c --config Specify config file + -h --help Show this help text + -c --config <path> Specify config file + -p --partials <path> Specify partials directory " # Declare storage declare -A TOKENS declare -A TEMPLATES +declare -A PARTIALS +PARTIALARGS= INDEX=0 # Parse arguments @@ -32,12 +36,22 @@ while [ "$#" -gt 0 ]; do ;; -c|--config) shift + PARTIALARGS="${PARTIALARGS} -c ${1}" if [[ -f "${1}" ]]; then while IFS='=' read key value; do TOKENS["$key"]="$value" done <<< "$(${DIR}/ini.sh ${1})" fi ;; + -p|--partials) + shift + PARTIALARGS="${PARTIALARGS} -p ${1}" + if [[ -d "${1}" ]]; then + while IFS=':' read name filename; do + PARTIALS["$name"]="${filename}" + done <<< "$(find "${1}" -type f -printf "%P:%p\n")" + fi + ;; *) if [[ -f "${1}" ]]; then TEMPLATES[$INDEX]="${1}" @@ -55,12 +69,25 @@ if [ "${INDEX}" -eq 0 ]; then exit 1 fi -# Replace tokens by values +# Handle all given templates for templatefile in "${TEMPLATES[@]}"; do CONTENT=$(cat $templatefile); + + # Replace tokens for token in "${!TOKENS[@]}"; do CONTENT=${CONTENT//"{{$token}}"/"${TOKENS[$token]}"} done + + # Handle partials + for partial in "${!PARTIALS[@]}"; do + if [[ "${CONTENT}" == *"{{>${partial}}}"* ]]; then + PARTIALCONTENT="$(${DIR}/${PROGNAME} ${PARTIALARGS} ${PARTIALS[$partial]})" + CONTENT=${CONTENT//"{{>$partial}}"/"${PARTIALCONTENT}"} + fi + done + + # Output the result echo -e "$CONTENT" done +