{{#foreach}} can be used with any associative array
no need to re-invoke the ITEMS function
can choose the namespacing - (can usefoo.bar, not hard-coded to items.foo)
will enable a nice refactor
more DRY:
one function to parse lots of different assoc arrays, instead of one func for each!
more de-coupling of templates and shell code
fewer shell funcs required to get a template parsing an assoc array
better separation of data and templates
fewer functions will need to be called in the templates generally
templates can more often refer directly to the array data being parsed
Syntax
Let's assume we have these arrays available in the current environment when processing our templates:
# create some associative arrays
declare -A link1=([url]=foo.com [title]=foo)
declare -A link2=([url]=bar.com [title]=bar)
# add references to them to an indexed array
declare -a header_links=(link1 link2)
And here is how foreach can use that array data in the templates:
{{#foreach link in header_links}}
{{link.title}} - {{link.url}}
{{/foreach}}
The function
foreach() {
# Trying to use unique names
local foreachSourceName foreachIterator foreachEvalString foreachContent
foreachContent=$(cat)
if [[ "$2" != "as" && "$2" != "in" ]]; then
echo "Invalid foreach - bad format."
elif [[ "$(declare -p "$1")" != "declare -"[aA]* ]]; then
echo "$1 is not an array"
else
foreachSourceName="${1}[@]"
for foreachIterator in "${!foreachSourceName}"; do
foreachEvalString=$(declare -p "$foreachIterator")
foreachEvalString="declare -A $3=${foreachEvalString#*=}"
eval "$foreachEvalString"
echo "$foreachContent" | mo
done
fi
}
Benefits:
{{#foreach}}
can be used with any associative arrayITEMS
functionfoo.bar
, not hard-coded toitems.foo
)Syntax
Let's assume we have these arrays available in the current environment when processing our templates:
And here is how
foreach
can use that array data in the templates:The function
See: https://github.com/tests-always-included/mo/blob/master/demo/function-for-foreach