Rendering an Array via Mustache

48 Views Asked by At

So I've got some data

{"facility":[{"ID":"A1A123","Name":" Anytown Health Centre PHCY","RegionID":1}]}

And I'd like to render it using a Mustache template that can be used to render either a single html table row, or multiple rows i.e. the object in the array can be 1 or greater.

The template looks like this

{{#facility}}
<form hx-put="/facility/{{ID}}">
  <div>
    <label>Name</label>
    <input type="text" name="Name" value="{{Name}}">
  </div>
  <div>
    <label>Region</label>
    <input type="text" name="RegionID" value="{{RegionID}}">
  </div>
</form>
{{/facility}}

So I can see the mismatch between my template looking for data in the form of facility.ID etc.

How do I structure the template to iterate over an array data tagged "facility" inside of an object ?

1

There are 1 best solutions below

1
David Moorhouse On

OK, so after 45 mins of google and some playing around I've got a working template which I'll share back here (in case I need to do this again in 3 years LOL) and for others to stumble across.

enter code here
{{#facility}}
{{#}}
<form hx-put="/facility/{{ID}}">
  <div>
    <label>Name</label>
    <input type="text" name="Name" value="{{Name}}">
  </div>
  <div>
    <label>Region</label>
    <input type="text" name="RegionID" value="{{RegionID}}">
  </div>
</form>
{{/}}
{{/facility}}

The key is to allow for the extra level of iteration. Mustache does not care if it is iterating over an object (by name) or an array (by ordinal)