Friday, 23 February 2018

Scala + HTML

Scala's support for inline xml can be used to render HTML, making template languages traditionally used witin web application's redundant. This approach is used by the Apache Spark Web UI and is similar to the approach taken by modern web frameworks such as React.

This also means that the view's would be type safe, i.e  if person.firstname was removed, the view would fail to compile. So errors can be cought sooner.

The code below demonstrates the approach:
    //define a class
    case class Person(firstName: String, lastName: String)

    //create a list of people, this will be the model
    val people = List(
                    Person("Riz", "Fujas"),
                    Person("John", "Smith"),
                    Person("Fred", "Clause")
                )

    val view  =
      <div class="container">
        <table>
          <tr>
            <th>First Name</th>
            <th>Second Name</th>
          </tr>

          {people.map{ person =>
            <tr>
              <td>{person.firstName}</td> 
              <td>{person.lastName}</td>
            </tr>
          }}
        </table>
      </div>


    println(view)


The println(view) will produce the following output:

<div class="container">
  <table>
    <tr>
       <th>First Name</th>
        <th>Second Name</th>
    </tr>
<tr> <td>Riz</td> <td>Fujas</td> </tr> <tr> <td>John</td> <td>Smith</td> </tr> <tr> <td>Fred</td> <td>Clause</td> </tr> </table> </div>






No comments:

Post a Comment