mirror of
https://github.com/tests-always-included/mo.git
synced 2024-12-18 16:27:52 +00:00
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:
parent
3516cdd631
commit
5dfb1cd96a
16
demo/associative-arrays
Executable file
16
demo/associative-arrays
Executable 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
|
30
mo
30
mo
@ -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
|
||||
#
|
||||
# Parameters:
|
||||
@ -531,7 +552,7 @@ mustache-partial() {
|
||||
# $1: Name of environment variable or function
|
||||
# $2: Current context
|
||||
mustache-show() {
|
||||
local MUSTACHE_NAME_PARTS
|
||||
local JOINED MUSTACHE_NAME_PARTS
|
||||
|
||||
if mustache-is-function "$1"; then
|
||||
CONTENT=$($1 "")
|
||||
@ -542,7 +563,12 @@ mustache-show() {
|
||||
mustache-split MUSTACHE_NAME_PARTS "$1" "."
|
||||
|
||||
if [[ -z "${MUSTACHE_NAME_PARTS[1]}" ]]; then
|
||||
if mustache-is-array "$1"; then
|
||||
eval mustache-join JOINED "," "\${$1[@]}"
|
||||
echo -n "$JOINED"
|
||||
else
|
||||
echo -n "${!1}"
|
||||
fi
|
||||
else
|
||||
# Further subindexes are disallowed
|
||||
eval 'echo -n "${'"${MUSTACHE_NAME_PARTS[0]}"'['"${MUSTACHE_NAME_PARTS[1]%%.*}"']}"'
|
||||
@ -639,7 +665,7 @@ mustache-test() {
|
||||
|
||||
if mustache-is-array "$1"; then
|
||||
# Arrays must have at least 1 element
|
||||
eval '[[ "${#'"$1"'}" -gt 0 ]]' && return 0
|
||||
eval '[[ "${#'"$1"'[@]}" -gt 0 ]]' && return 0
|
||||
else
|
||||
# Environment variables must not be empty
|
||||
[[ ! -z "${!1}" ]] && return 0
|
||||
|
Loading…
Reference in New Issue
Block a user