Question

I am new to groovy and grails, hence this simple doubt. I have a map like this: [0:[A,B,C,D], 1:[a,b,c,d]]. I want to display it as follows:
A: a
B:b
C:c
D:d

How do you display the data column wise? The .gsp I have now is shown below and all it does is display the values row wise.

 <!DOCTYPE html>
<html>
    <head>
        <meta name="layout" content="main">
        <title>Parsed Map</title>
    </head>
    <body>      
        <table>
            <g:each in="${myMap}" var="element">
                <tr>
                    <g:each in="${element.value }" >
                            <th>${it}</th>
                         </g:each>

                    </tr>
                </g:each>
        </table>                
    </body>
</html>

Pointing me in right direction for understanding maps in groovy will also be appreciated. Thank you.

Was it helpful?

Solution

Assuming that you have already validated that the columns and header lists have the same number of elements, you could do something like this...

<html>
    <head>
        <meta name="layout" content="main">
        <title>Parsed Map</title>
    </head>
    <body>
        <table>
            <g:each var="heading" in="${headings}" status="counter">
                <tr>
                    <th>${heading}</th>
                    <td>${values[counter]}</td>
                </tr>
            </g:each>
        </table>
    </body>
</html>

OTHER TIPS

I assume your example is a simplified version of your real problem. Depending on what you are really trying to do, you have a number of options. A simple thing might be like this (organize the table however you like, but this should give you the idea...):

// grails-app/controllers/com/demo/DemoController.groovy
package com.demo

class DemoController {

    def index() {
        // presumably you got this Map from somewhere and it isn't hardcoded here
        def someMap = [0:['A', 'B', 'C', 'D'], 1:['a', 'b', 'c', 'd']]

        def headings = someMap[0]
        def values = someMap[1]

        [headings: headings, values: values]
    }
}


// grails-app/views/demo/index.gsp
<html>
<head>
    <meta name="layout" content="main">
    <title>Parsed Map</title>
</head>
<body>
    <table>
        <tr>
            <g:each var="heading" in="${headings}">
                <th>${heading}</th>
            </g:each>
        </tr>
        <tr>
            <g:each var="value" in="${values}">
                <th>${value}</th>
            </g:each>
        </tr>
    </table>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top