Pregunta

I'm using jsRender and I wanted to display my data as columns rather then the rows I am returning. I want to pivot the data - is this something that can be done with jsRender. I can't get the data pivoted in SQL so my only option is to do it myself.

This is basically what I am after. I want to write the column names myself.


Header | Row 1 | Row 2 | Row 3 |


Column Blah | Row data | Row data | Row data


More blah | Row data | Row data | Row data


I have tried to use the {{for}} loop for table cell but I just don't know where to start.

UPDATE: After Boris's suggestion I have tried the suggested code. Although I as it's not formatting properly I have included it here.

This is an excerpt of my JSON source:

{
  "Layers": {
    "Layer": [
      {
    "@LayerID": "1",
    "RiskRef": {
      "@ColVal": "Contract/Section Number",
      "#text": "PUSNA11000392/1"
    },
    "ContractStatus": {
      "@ColVal": "New, Renewal or NTU?",
      "#text": "New"
    },
    "AdjustRate": {
      "@ColVal": "Adjustable Rate",
      "#text": "0.53%"
    },

And my jsRender javaScript code is:

<script id="xolDetailsTemplate" type="text/x-jsrender">
            {{for Layers}}
                {{for >#data["Layer"]}}
                <td>{{>#data["@LayerID"]}}</td>
                {{/for}}
            {{/for}}
</script>
¿Fue útil?

Solución

If your data is model = { people: [{firstName: "Jo", lastName: "Colby"}, ...] }

you can use the following template to render a people array, pivoted rows to columns:

<tbody>
    <tr><td>First Name</td>{{for people}}<td>{{>firstName}}</td>{{/for}}</tr>
    <tr><td>Last Name</td>{{for people}}<td>{{>lastName}}</td>{{/for}}</tr>
</tbody>

In your comment below you say that your data is has field names like "@foo". Lets consider this example: model = { "people": [{"@firstName": "Jo", "@lastName": "Colby"}}, ...] }.

You can render this with a template as follows:

<tbody>
    <tr><td>First Name</td>{{for people}}<td>{{>#data["@firstName"]}}</td>{{/for}}</tr>
    <tr><td>Last Name</td>{{for people}}<td>{{>#data["@lastName"]}}</td>{{/for}}</tr>
</tbody>

If the field name has non JavaScript name characters, such as "@" that is where you need to use the syntax #data["@xxx"].

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top