Using either Java or Groovy, iterate through a hashmap and showcase an HTML table within a Velocity template

Just a heads up: Some users may have trouble reading code comments. For the record, this is not related to any homework assignment. I'm attempting to combine HTML and a hashmap for the first time. Despite searching for explanations online, nothing seems to be working for me. Whenever I use the "#" symbol, it gives me errors.

Objective: Use Groovy or Java to present an HTML table with HashMap results.
Pseudo Code: Please excuse any syntax errors and pay attention to the tr loop.

import groovy.xml.MarkupBuilder; // feel free to recommend 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
    {
     // Problem: Syntax error occurs when using "#", I don't know how to concatenate 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>

Answer №1

Here is a simple way to define a hashmap in Groovy without using curly braces:

  • To display all entries in a map in a table, you can use the following code snippet.
import groovy.xml.MarkupBuilder
def hashmap = [Array1:['a','b','c'], Array2:[1,2,3]]
StringWriter writer = new StringWriter()
def builder = new MarkupBuilder(writer)
builder.html {        
   hashmap.collect{ key, valueList ->     
        table {
           valueList.collect {tr it}
        }
    }    
}
println writer.toString()

You can test this code online by visiting this demo link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a Method to Detect Keypress Event on Anchor Element

Within our application, we have implemented anchor tags as buttons to enable specific style implementations. An interesting feature of the anchor tag is that it does not receive focus when navigating through tabs. Although we have successfully implemented ...

Is there a method to construct this? It appears quite challenging to create the intricate lines

I want to achieve this specific layout, but I am unsure how to align the lines next to the boxes. Should I use display or position properties to accomplish this? Image illustrating my desired outcome ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

Run javascript code after the page has transitioned

Struggling to create a dynamic phonegap app with jQuery Mobile, the issue arises when loading JavaScript on transition to a new page. The structure of my index page is as follows: <body> <div data-role="page" id="homePage"> <div data- ...

The background image is not appearing on the div as expected

I've been attempting to create a div and set a background image for it using jQuery, but I seem to be facing issues. When I try setting the background color to white, it works fine. Here's the code snippet: function appendToDom(poster) { ...

various image proportions in HTML

I have an image with a ratio of 16:9 that I want to use on my website. On one of the pages, I display a list of products with images having a ratio of 340x265. When a user clicks on an item in the list, it takes them to the product page where the same im ...

pictures on the blog entries

I'm looking to customize the look of images within a section. I want to add borders to the images, but since they are being added dynamically as content in blog posts, I can't reference them directly. Can you recommend a way for me to achieve thi ...

Retrieving Data from Outside Source using AngularJS

Is there a way to retrieve JSON-Text-Stream data from a specific URL (e.g. SOMEURL/ean.php?id=4001513007704)? The returned result typically appears as follows: { "product": { "ean_id": "4001513007704", "title": "Gerolsteiner Mineralw ...

Unlocking the Power of Transition: Effortlessly Submitting a Form Post

After the modal finishes fading out, I want my form to be submitted and sent to the email file "refreshform.php". However, currently after the modal fades out, the form does not submit or post anything to the PHP file for sending the email. It simply fades ...

Is dividing a container into equal sections possible with flexbox?

Is there a way to create an HTML/CSS structure that divides a fixed-size container into three sections horizontally? The first section should expand based on its content, while the remaining two sections should evenly split the leftover space, with scrollb ...

Troubleshooting an Issue with MediaStreamRecorder in TypeScript: Dealing with

I've been working on an audio recorder that utilizes the user's PC microphone, and everything seems to be functioning correctly. However, I've encountered an error when attempting to record the audio: audioHandler.ts:45 Uncaught TypeError ...

Unfamiliar String Conversion to JSON in Java

Need assistance with parsing a JSON-formatted string obtained from a URL. The field and size of the data may vary, making it difficult to iterate over the structure of the JSON object. Here is an example of the string: {"_index":"my_index","_type":"my_t ...

An easy way to attach a Contextmenu to a specific element

I have implemented a scrolling feature for one of the div elements in my Application. Inside this div, there is a templated table with over 100 rows. Users are able to add or delete rows using a contextMenu. The contextMenu offers 4 options - AddTop, AddB ...

Angular input range slider that automatically rounds decimal values from the data bindings

I've implemented a range slider within an Angular form to capture and display recorded values. <input [formControlName]="object.id" [id]="object.id" type="range" [(ngModel)]="object.answer" [step]="objec ...

I am attempting to add user input to the parent container when the button is clicked, but for some reason it is

Recently delving into jquery, I attempted to dynamically add an input field to a parent div on button click, but encountered some difficulties. Specifically, my goal was to insert a div with an input element into the parent div identified by the id "join ...

The ion-item is refusing to be centered on the page

I'm having trouble centering an ion-item and it seems slightly off-center. The standard methods like text-align: center and adjusting padding in ion-content don't seem to be working for me. Can someone please assist? https://i.stack.imgur.com/QZ ...

What is the best way to capture a screenshot of a website using its URL?

I've been curious about the possibility of capturing a screenshot of a remote website using only a URL and some JavaScript code. This functionality is often seen on bookmarking sites. I can't help but wonder if this is achieved through a virtual ...

Style large and small text side by side with CSS styling

I've been trying to figure out how to position a smaller biography-style text next to this large title, but I'm having trouble finding a solution. I've experimented with float: left, float: right, and display: flex in my CSS code. Below is t ...

What could be causing the issue with the 100% height and 100% width not functioning properly on my ASPX page?

The CSS and HTML code work perfectly in an isolated test environment: body, html { height: 100%; min-height:600px; min-width:800px; overflow:hidden; margin:0;padding:0; } html {overflow:auto;} .fill {height:100%; width:100%; backgro ...

iOS devices will not scroll horizontally if there is a div that scrolls vertically within a div that scrolls horizontally

Picture a div that scrolls horizontally, housing two vertical-scrolling divs. You'll need to scroll left and right to navigate, then up and down inside the inner divs to read the content. /* RESET TO MINIMUM */ body, html { height: 100%; mar ...