tests-always-included / mo

Mustache templates in pure bash
Other
563 stars 67 forks source link

(Close Pending #62) Feature: Vars, Keys, and Values in Function Args #61

Closed Swivelgames closed 4 months ago

Swivelgames commented 1 year ago

Feature

As an extension of #56, this would allow passing @index, @key, ., or $varname as function arguments.

Example:

foo="bar"
arr1=("hello" "world")
declare -A DATA
DATA[rip]="hub"

uppercase() {
    echo -n "${1^^}"
}

Template:

<b>{{#uppercase $foo }}</b>
<b>{{#uppercase $DATA.rip }}</b>

{{#arr1}
    {{#uppercase .}}
{{/#arr1}}

{{#DATA}}
    {{#uppercase @key}} {{.}}
{{/DATA}}

Output:

<b>BAR</b>
<b>HUB</b>

    HELLO
    WORLD

    RIP hub

Justificaton

Implementation Considerations

This will require iterating through each of the arguments passed to a function in order to replace them with the key, index, or value.

Issues

One issue I foresee with the above feature is the use of $ as the prefix to denote a variable. For instance, if a function arg is a dollar amount or something similar, this might cause issues: {{#myfunc $10.00}}. Granted, I'm not even sure this is a valid use-case.

Some options we have available to us:

{{#myfunc $foo }}
{{#myfunc &foo }}
{{#myfunc #foo }}

Granted, there's this (albeit limited) option:

{{#foo}}
    {{myfunc .}}
{{/foo}}

But that would limit functions to receiving a single variable.

Swivelgames commented 1 year ago

I'm going to hold off on implementing passing variables until there's some discussion, but I'll at least throw together a proof-of-concept for passing @key and . and push it up as a PR. (Most likely tomorrow).

fidian commented 1 year ago

What I would absolutely love to see is a way to pass variables, strings, and other things to functions. Going off memory, I believe we currently have {{myfunc parameter}}. Only string parameters are allowed and the list is merely split on spaces. There's no way to pass in variable names, strings with spaces, etc. If I were to dream big (and possibly break backwards compatibility), I would support the following:

fidian commented 1 year ago

I'm not proposing that indirect values are solved here, but we allow for indirect values once they get decided upon.

fidian commented 1 year ago

Sorry for the rapid emails.

Another feature, if I were to have my ideal wish, would be to allow mustache inside mustache.

{{myfunc {{anotherFunc "thing"}}}} -> {{myfunc "result_of_anotherFunc"}}

Sadly, this would probably take rewriting the entire parser.

fidian commented 1 year ago

Function processing and handling of arguments has been greatly altered with #62. I think that the solution there would work to solve the problems here. Would you agree?