Moodle for mobile

Multidimensional array handling in mustache

Picture of Dani Palou
Re: Multidimensional array handling in mustache
Core developersMoodle HQParticularly helpful MoodlersPlugin developers

Copying here the discussion held in dev chat so other users can see it:

David Mudrák:

Mustache uses JSONable data so basically two supported data structures are:

* lists (in PHP speak, numeric arrays that _must_ have sequential indexes), or

* dictionaries/hashes (in PHP speak, associative arrays or objects)

Common problem is when trying to work with numerical arrays with non-sequential indexes, such as results of get_records()

Igor Sazonov:

Hi, David! yes, i understand about sequal in indexes in numerical arrays, for example, i have array item like `$item[0][0][0]`, so in Mobile mustache template i cant dispay it. I mean not web-based mustache but Mobile with `<% %>` tags from here

or array item like $item[0][0]['associative'] and nother kinds)

David Mudrák:

Correct. As far as I know, there is no way in Mustache to address list items. Only iterate through them.

So if you pass it a list of items, there is no way in Mustache to display the first one and stop.

Things like {{a.0}} only work in some implementations as side effects

Igor Sazonov:

Then I don't understand how to fetch a key in array loop)

David Mudrák:

You can't. You have to pass it is a list of objects with like "index" and "value" properties.

[{ix: 1, val: 'Foo'}, {ix: 2, val: 'Bar'}]

Igor Sazonov:

Yes, I know, I did that) but it works only for simple arrays, not multidimensional

David Mudrák:

Well, "value" can be another list, no?

It is a bit counter-intuitive if you are used to PHP structures, I know.

Average of ratings: -