Home > front end >  How do I access values on an array of objects in mustache template in moodle?
How do I access values on an array of objects in mustache template in moodle?

Time:02-23

I extracted records from the database and assigned them to the variable $results and I'm trying to loop through this array of objects but can't access anything in the objects and it only runs once despite there being 3 objects.

Here is what I get from var_dump($results);:

array(3) 
{ 
  [3]=> object(stdClass)#261 (3) { 
    ["id"]=> string(1) "3" ["grade"]=> string(1) "A" ["score"]=> string(2) "95" } 
  [2]=> object(stdClass)#260 (3) { 
    ["id"]=> string(1) "2" ["grade"]=> string(1) "A" ["score"]=> string(2) "90" } 
  [1]=> object(stdClass)#259 (3) { 
    ["id"]=> string(1) "1" ["grade"]=> string(1) "C" ["score"]=> string(2) "50" } 
}

Here is what I'm trying in the mustache template:

      <table>
        <tr>
          <th>Score</th>
          <th>Grade</th>
        </tr>
        {{#results}}
          <tr>
            <td>{{ score }}</td>
            <td>{{ grade }}</td>
          </tr>
        {{/results}}
      </table>

CodePudding user response:

The problem I can see is that the $results array has keys that are not consecutive values, starting at 0, so it is treated as an object with specific member values and cannot be looped through in Mustache.

If you want to loop through it in Mustache, then call:

$results = array_values($results);

Before passing it into the Mustache template - after that, I think it should work.

  • Related