Home / TeaVM Patterns and Pitfalls / TeaVM Patterns and Pitfalls     frequal.com

Creating an HTML List from a Java List with Flavour

Make a List Property in the View Class

In your View class, make a property holding a list of objects. I will hardcode it here, but in a real system it could come from a back-end service.
  public List listBooks = Arrays.asList(
      new Book("Congo", "Michael Crichton"),
      new Book("Insomnia", "Steven King"),
      new Book("Hunger Games", "Suzanne Collins")
  );

Make the Template Loop Over the List

In the template, use <std:foreach> to loop over the list from the view class. For each book, add a list item with the title and author using the <html:text> element.
  <ol>
    <std:foreach var="book" in="listBooks">
      <li> <html:text value="book.title"/> by <html:text value="book.author"/>
    </std:foreach>
  </ol>

The Result

The resulting HTML:
  1. Congo by Michael Crichton
  2. Insomnia by Steven King
  3. Hunger Games by Suzanne Collins

Next Steps

Some things you could do with std:foreach
  1. Build a table
  2. Build a bunch of divs to hold images
  3. Draw shapes on a Canvas

Last modified on 12 Dec 2018 by AO

Copyright © 2024 Andrew Oliver