sc0ttj / mdsh

A simple static site generator, using Markdown and Bash
https://sc0ttj.github.io/mdsh/
10 stars 0 forks source link

`foreach` iterator #82

Closed sc0ttj closed 4 years ago

sc0ttj commented 5 years ago

Benefits:

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
}

See: https://github.com/tests-always-included/mo/blob/master/demo/function-for-foreach

sc0ttj commented 4 years ago

Included in https://github.com/sc0ttj/mdsh/pull/85, closing.