mustache
mustache copied to clipboard
Selector for index in an array: items.0.name
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.
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}}
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
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!
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)