Better associative array handling

Bug:  Did not properly detect the length of an array in mustache-test
because I neglected to use `[@]` after the array name.  This closes
issue #6.

Feature:  Made {{ARRAY_NAME}} implode array values with commas.

Feature:  Added an associative array demo script.
This commit is contained in:
Tyler Akins 2015-05-05 10:46:06 -05:00
parent 3516cdd631
commit 5dfb1cd96a
2 changed files with 47 additions and 5 deletions

16
demo/associative-arrays Executable file
View File

@ -0,0 +1,16 @@
#!/bin/bash
declare -A DATA
DATA=([one]=111 [two]=222)
cat <<EOF | . ~/bin/mo
Accessing data directly:
DATA: {{DATA}}
One: {{DATA.one}}
Two: {{DATA.two}}
Things in DATA:
{{#DATA}}
Item: {{.}}
{{/DATA}}
EOF

32
mo
View File

@ -307,6 +307,27 @@ mustache-is-standalone() {
} }
# Join / implode an array
#
# Parameters:
# $1: Variable name to receive the joined content
# $2: Joiner
# $3-$*: Elements to join
mustache-join() {
local JOINER PART RESULT TARGET
TARGET=$1
JOINER=$2
RESULT=$3
shift 3
for PART in "$@"; do
RESULT="$RESULT$JOINER$PART"
done
local "$TARGET" && mustache-indirect "$TARGET" "$RESULT"
}
# Read a file # Read a file
# #
# Parameters: # Parameters:
@ -531,7 +552,7 @@ mustache-partial() {
# $1: Name of environment variable or function # $1: Name of environment variable or function
# $2: Current context # $2: Current context
mustache-show() { mustache-show() {
local MUSTACHE_NAME_PARTS local JOINED MUSTACHE_NAME_PARTS
if mustache-is-function "$1"; then if mustache-is-function "$1"; then
CONTENT=$($1 "") CONTENT=$($1 "")
@ -542,7 +563,12 @@ mustache-show() {
mustache-split MUSTACHE_NAME_PARTS "$1" "." mustache-split MUSTACHE_NAME_PARTS "$1" "."
if [[ -z "${MUSTACHE_NAME_PARTS[1]}" ]]; then if [[ -z "${MUSTACHE_NAME_PARTS[1]}" ]]; then
echo -n "${!1}" if mustache-is-array "$1"; then
eval mustache-join JOINED "," "\${$1[@]}"
echo -n "$JOINED"
else
echo -n "${!1}"
fi
else else
# Further subindexes are disallowed # Further subindexes are disallowed
eval 'echo -n "${'"${MUSTACHE_NAME_PARTS[0]}"'['"${MUSTACHE_NAME_PARTS[1]%%.*}"']}"' eval 'echo -n "${'"${MUSTACHE_NAME_PARTS[0]}"'['"${MUSTACHE_NAME_PARTS[1]%%.*}"']}"'
@ -639,7 +665,7 @@ mustache-test() {
if mustache-is-array "$1"; then if mustache-is-array "$1"; then
# Arrays must have at least 1 element # Arrays must have at least 1 element
eval '[[ "${#'"$1"'}" -gt 0 ]]' && return 0 eval '[[ "${#'"$1"'[@]}" -gt 0 ]]' && return 0
else else
# Environment variables must not be empty # Environment variables must not be empty
[[ ! -z "${!1}" ]] && return 0 [[ ! -z "${!1}" ]] && return 0