tests-always-included / mo

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

Feature: Key and Index Accessors Inside Loops #56

Closed Swivelgames closed 1 year ago

Swivelgames commented 1 year ago

Feature

Presently, it's possible to output the value of current loop context, but it's not possible to output the key.

The proposal would add both {{@index}} and {{@key}} as possible cases.

Justificaton

While this feature doesn't add logic constructs, it does exist in Handlebars.js, an off-shoot of Mustache. It's important to note that Handlebars.js is not faithful to Mustache's definition of being Logic-less.

However, mo is already forwards-compatible with Associative Arrays in Bash, including in some advanced-aspects like the form of dot-notation that mo supports. None of the aforementioned are considered Logical operations. These are just data accessors.

Additionally, the keys in an associative array are often useful to Bash users. Without this, the keys iterating over an associative array are inaccessible and useless to template writers.

Implementation Considerations

Because of the way mo is implemented, the addition of this is minimal, since the key is already maintained within $moCurrent.

Swivelgames commented 1 year ago

UPDATE Just tested this with Bash 3.1 and Bash 3.2 and mo executed successfully!

Just like the other Associative Array features already in mo, these features are compatible with Bash 4.0-5.1.

This was implemented successfully in #57

fidian commented 1 year ago

Everything looks good in #57, but I would like two changes.

First, I think @key and @index appear to do the same thing. I'm not really seeing a difference between them except @index appears to filter out non-numerics. Can their logics be combined? Is there an advantage to keeping them separate?

Secondly, please update README.md with the important details and possibly include it in an example. I'm thinking you could add an "Enhancements" section right before "Concessions", then briefly detail how it works and possibly link to a demo if the example starts to get long.

Swivelgames commented 1 year ago

I'm glad you addressed that. I included @index after referencing the Handlebars documentation, since we're borrowing @key from there. I wasn't sure if there was a use-case to include @index, so I went ahead and threw it in there for posterity's sake. But I am totally fine with removing it... @key will give you either the index or the named portion, regardless of what you're iterating over.

Also, I'll absolutely updated the README.md. After pushing all of these up I was scrolling through and thinking I probably should have haha. I'll get those added and update the PR.

Swivelgames commented 1 year ago

@fidian Done!

fidian commented 1 year ago

Closing this. Will continue in #57.