robertknight / qt-mustache

Mustache templating library for C++ using Qt
85 stars 28 forks source link

Accessing Array item by index in template not supported #21

Open sketchbook22 opened 8 years ago

sketchbook22 commented 8 years ago

missing this common feature: https://github.com/janl/mustache.js/issues/158 syntex like this {{foo.2}} to access the value at index 2 of list foo "will work with most mustache implementations" but not this one.

robertknight commented 8 years ago

Indeed, this is very much a bare-bones mustache implementation. I'm probably not going to get around to implementing this myself but I'll happily take a PR.

sketchbook22 commented 8 years ago

adapting the existing key/value handling to support this seems tricky. there is already some logic to split the key on "." which is in QVariant QtVariatnContext::value, which i worry would cause a conflict.

alternatively, similar results are also commonly available through this syntax: {{2}} which would access the value at index 2 of all values in the current section... would I evaluate m_contextStack to infer the current section?

robertknight commented 8 years ago

There is a function variantMapValue() which is responsible for extracting the value from a data structure that corresponds to a given key string. Currently that only supports QMap and QHash data structures. To support the "list." syntax, I think you'll just need to extend that to support array-like structures (QList, QVector etc.). This would also support the "" syntax on its own if the value on the context stack is a list.

I believe there was some work done to add generic support for performing lookups in QVariant values which were associative (map-like) data structures or indexed-based (list-like) ones. I don't see that in the current API docs but it might be worth asking about on IRC.