Updated function calls to pass in current element when looping

This commit is contained in:
Joseph Dalrymple 2023-03-31 05:52:13 -05:00
parent a62541fc98
commit 2707adaa05
5 changed files with 83 additions and 3 deletions

48
demo/function-args-loops Executable file
View File

@ -0,0 +1,48 @@
#!/usr/bin/env bash
# Example for how #54 can get implemented.
cd "$(dirname "$0")" # Go to the script's directory
# The links are associative arrays
declare -a links
declare -A names urls
links+=(resque)
names[resque]=Resque
urls[resque]=http://example.com/resque
links+=(hub)
names[hub]=Hub
urls[hub]=http://example.com/hub
links+=(rip)
names[rip]=Rip
urls[rip]=http://example.com/rip
# helper functions
link_name() {
# Trying to use unique names
local key
key=$(cat)
echo ${names[$key]}
}
link_url() {
# Trying to use unique names
local key
key=$(cat)
echo ${urls[$key]}
}
# Source mo in order to work with arrays
. ../mo
# Process the template
cat <<EOF | mo --allow-function-arguments
Here are your links:
{{#links}}
* [{{link_name}}]({{link_url}})
{{/links}}
EOF

15
mo
View File

@ -769,9 +769,13 @@ moParse() {
moFullTagName moTag "$moCurrent" "$moTag"
moContent=${moContent[1]}
if [[ ! -z "$moCurrent" ]]; then
moBlock=$(moShow "$moCurrent" "$moCurrent")
fi
# Now show the value
# Quote moArgs here, do not quote it later.
moShow "$moTag" "$moCurrent" "$moArgs"
moShow "$moTag" "$moCurrent" "$moArgs" "$moBlock"
;;
'&'*)
@ -791,8 +795,12 @@ moParse() {
moArgs=${moArgs:${#moTag}}
moFullTagName moTag "$moCurrent" "$moTag"
if [[ ! -z "$moCurrent" ]]; then
moBlock=$(moShow "$moCurrent" "$moCurrent")
fi
# Quote moArgs here, do not quote it later.
moShow "$moTag" "$moCurrent" "$moArgs"
moShow "$moTag" "$moCurrent" "$moArgs" "$moBlock"
;;
esac
@ -880,6 +888,7 @@ moPartial() {
# $1 - Name of environment variable or function
# $2 - Current context
# $3 - Arguments string if $1 is a function
# $4 - Content string if $1 is a function
#
# Returns nothing.
moShow() {
@ -887,7 +896,7 @@ moShow() {
local moJoined moNameParts moContent
if moIsFunction "$1"; then
moCallFunction moContent "$1" "" "$3"
moCallFunction moContent "$1" "$4" "$3"
moParse "$moContent" "$2" false
return 0
fi

View File

@ -0,0 +1,9 @@
arr=(
"test1"
"test2"
)
testArgs() {
value=$(cat)
echo "$value - $MO_FUNCTION_ARGS"
}

View File

@ -0,0 +1,8 @@
No args: [test1 - ] - done
One arg: [test1 - one] - done
Multiple arguments: [test1 - aa bb cc 'x' " ! {[_.|] - done
Evil: [test1 - bla; cat /etc/issue] - done
No args: [test2 - ] - done
One arg: [test2 - one] - done
Multiple arguments: [test2 - aa bb cc 'x' " ! {[_.|] - done
Evil: [test2 - bla; cat /etc/issue] - done

View File

@ -0,0 +1,6 @@
{{#arr}}
No args: [{{testArgs}}] - done
One arg: [{{testArgs one}}] - done
Multiple arguments: [{{testArgs aa bb cc 'x' " ! {[_.| }}] - done
Evil: [{{testArgs bla; cat /etc/issue}}] - done
{{/arr}}