Nitesh Virani Nitesh Virani - 2 months ago 25
Scala Question

Generate dynamic HTML file

I am new to Scala. I have predefined html file. I want to plug dynamic content in HTML file.

e.g.
$for(products in product)
<div>product.name</div>
<div>product.description</div>


Here
products
is Scala collection. I can load html file and feed dynamic values(
products
).

Would you advise me how to do this in Scala?

Answer

Twirl templates

compiled, typesafe, composable, scala inside Html tags (akin angular js [javscript inside Html])

Twirl templates enable you to write scala inside a html, its typesafe, gets compiled to functions and are composable as well.

orders.scala.html

@(customer: Customer, orders: List[Order])

<h1>Welcome @customer.name!</h1>

<ul>
@for(order <- orders) {
  <li>@order.title</li>
}
</ul>

Without any library

Scala has good support for string interpolation and also provides triple quote syntax for declaring strings with espace characters which is very handy. You can produce dynamic Html using this simple method

 case class Product(name: String)

  case class Html(content: String)

  def produceHtml(products: List[Product]): Html = {
    Html {
      products.map { product =>
        s"""
           |<div> ${product.name} </div>
        """.stripMargin
      }.mkString("\n")
    }
  }