mustache icon indicating copy to clipboard operation
mustache copied to clipboard

Selector for index in an array: items.0.name

Open mattslocum opened this issue 3 years ago • 4 comments

In other implementations of mustache there is the ability to write a selector into an array by the index. Ex: items.0.name. This doesn't seem possible with the golang implementation. I understand how it is potentially free in JS, but it would require extra effort in golang. Is this something that could be supported in the future?

Similar requests by other libraries (with mixed results): Python: https://github.com/defunkt/pystache/issues/196 C#: https://github.com/DanieleScipioni/Mustache/issues/2 Erlang: https://github.com/soranoba/bbmustache/issues/41 Swift: https://github.com/groue/GRMustache.swift/issues/2

Alternative idea: Methods that support params. golang's text/template supports index lookup with functions.

{{ (index .items 0).Name }}

try it: https://play.golang.org/p/dgIMARysMOX

It looks like this library already supports functions on the struct, but it didn't seem to support params. If it did, then a getter could be added as needed.

mattslocum avatar Sep 14 '21 20:09 mattslocum

Also would advocate for this. Without this, it's probably impossible to do something like:

if len(array) > 0:
    dosomething()

Something like this would be cool:

{{array.0}}
Yep, your list has at least one element. Here it is:
{{array}} {{.}} {{/array}}
{{/array.0}}

ptrxyz avatar Jun 27 '22 22:06 ptrxyz

I can see how this would be valuable, but as it's not part of the mustache spec, it's not something I plan to add to this library

cbroglie avatar Jul 12 '22 04:07 cbroglie

Hi all, I need this for my project, so I've added support to my fork and sent a PR (#85) - I hid it under Experimental flag to make sure it does not interfere with the spec.

Hope it helps!

vpavlin avatar Feb 02 '23 15:02 vpavlin

I made a workaround to pre-transform the data so it can be accessed via index dot notation:

def transform_data(data):
        """Transform data to make indexed array access possible."""
        def transform(item):
            if isinstance(item, list):
                return {str(i): transform(subitem) for i, subitem in enumerate(item)}
            elif isinstance(item, dict):
                return {key: transform(value) for key, value in item.items()}
            else:
                return item

        return transform(data)

esteininger avatar Feb 01 '24 15:02 esteininger