Dynamic tables using Mustache using dynamic arrays

I am wondering if there is a more elegant solution for my current solution for the next problem.

Problem: Generate dynamic tables from a dynamic array using Mustache if:

  • The total number of columns is unknown.
  • Only one or two column names are known and should be conditionally displayed
  • Assistant functions many not used
  • Data is provided only in arrays. Not class modeling

A typical dataset with a variable column, in which the identifier is the only column that should always be provided:

[id*] [Col-1] [Col-2] [Col-3] ...(more) 1 'Foo' 'Bar' 'Baz' ...(more) 2 'Foo' 'Bar' 'Baz' ...(more) 3 'Foo' 'Bar' 'Baz' ...(more) ... (more) 

Current solution: mix variational key names with a constant key name In this example below, variable keys are based on different column names that are dynamically generated from the data source, which ("id", "name", "legal_name", "email", "signon_email "," editable ") and constants the key name is" field "

Array example:

 array (size=6) 0 => array (size=2) 'id' => string '10' (length=2) 'field' => string 'id' (length=2) 1 => array (size=2) 'value' => string 'J. Doe' (length=8) 'field' => string 'name' (length=8) 2 => array (size=2) 'value' => string 'Jane Doe' (length=8) 'field' => string 'legal_name' (length=8) 3 => array (size=2) 'value' => string ' Jane@Doe.com ' (length=12) 'field' => string 'email' (length=12) array (size=6) 0 => array (size=2) 'id' => string '11' (length=2) 'field' => string 'id' (length=2) 1 => array (size=2) 'value' => string 'Jon Doe' (length=8) 'field' => string 'name' (length=8) 2 => array (size=2) 'value' => string 'John Doe' (length=8) 'field' => string 'legal_name' (length=8) 3 => array (size=2) 'value' => string ' John@Doe.com ' (length=12) 'field' => string 'email' (length=12) 

Template:

 {{#rows}} <tr>{{#fields}} <td>{{#id}}<a href="foo/{{id}}">{{id}}</a>{{/id}} {{^id}}{{field}}: {{value} {{/id}} </td> {{/fields}} </tr> {{/rows}} 

Result:

 <tr> <td><a href="foo/10">10</a></td> <td>name: J Doe</td> <td>legal_name: Jane Doe</td> <td>email: Jane@Doe.com </td> </tr> <tr> <td><a href="foo/11">11</a></td> <td>name: Jon Doe</td> <td>legal_name: John Doe</td> <td>email: John@Doe.com </td> </tr> 

Data redundancy is not a concern since data sets are really small. Most importantly, we want a language-neutral solution (no lambda).

+2
source share

Source: https://habr.com/ru/post/1439124/


All Articles