Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mattslocum opened this issue Sep 14, 2021 · 4 comments
Open

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

mattslocum opened this issue Sep 14, 2021 · 4 comments

Comments

@mattslocum
Copy link

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: defunkt/pystache#196
C#: DanieleScipioni/Mustache#2
Erlang: soranoba/bbmustache#41
Swift: groue/GRMustache.swift#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.

@ptrxyz
Copy link

ptrxyz commented Jun 27, 2022

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}}

@cbroglie
Copy link
Owner

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

@vpavlin
Copy link

vpavlin commented Feb 2, 2023

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!

@esteininger
Copy link

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants