Search code examples
javahtmlgroovyhashmapvelocity

Java or Groovy: loop through hashmap and display html table in Velocity template


DISCLAIMER: Some users cannot read the code comments. This is NOT homework. I am trying to concatenate html and a hashmap. I never did this before. None of the explanations I found out there work. If I use "#" it complains.

Task: using Groovy or Java, display HTML table with HashMap results.
Pseudo Code: please forgive any syntax issues and focus on the tr loop

import groovy.xml.MarkupBuilder; // feel free to suggest another package

def hashmap = Collections.synchronizedMap(new HashMap());
hashmap = {Array1:['a','b','c'], Array2:[1,2,3]};

hashmap.each
{
    a1, a2 -> "${a1}: ${a2}"
    def target = a2['Array2'];

    StringWriter st = new StringWriter();
    def mkup = new MarkupBuilder(st);
    mkup.html
    {
     // Issue: syntax error using "#", I do not now how to concat both objects

        #foreach( $t in $target ) 
        tr
        {
         $t.toString()
        }
        #end
    }

    String desiredOutput = st.toString();
}

Desired output:

<table>
    <tr>1</tr>
    <tr>2</tr>
    <tr>3</tr>
</table>

Solution

  • Here you go:

    • For defining hashmap, it is simple in groovy, no need to use {..}
    • Assuming that all the entries in map should be shown in the table.
    import groovy.xml.MarkupBuilder
    def hashmap = [Array1:['a','b','c'], Array2:[1,2,3]]
    StringWriter st = new StringWriter()
    def mkup = new MarkupBuilder(st)
    mkup.html {        
       hashmap.collect{ k, vList ->     
            table {
               vList.collect {tr it}
            }
        }    
    }
    println st.toString()
    

    You can quickly try it online demo