praxnet praxnet - 1 month ago 13
Scala Question

How to do sum on the elements from list of Objects in Scala in play html template?

I am receiving csrList in my Play HTML Template, I want to Construct table in my HTML using csrList Object, and I want total of each element to be shown in TOTALs row.

I do not want to send Totals as one more object in List, I want to do totals in template only using scala's syntactic sugar

is it possible ?

e.g. Play Template

@(csrList: List[CSR])
....
....
<table id="abc">
<tr>
<th></th>
<th>LTC</th>
<th>LTI</th>
<th>LTS</th>
</tr>

<tr>
<th> TOTALs </th>
<th> ???? </th>
<th> ???? </th>
<th> ???? </th>
</tr>

@for(csr <- csrList) {
<tr>
<td> @(csr.name) </td>
<td> @(csr.ltc) </td>
<td> @(csr.lti) </td>
<td> @(csr.lts) </td>
</tr>
}
</table>


for Ref. following is Object Structure

case class CSR(name: String, ltc: Int, lti : Long, lts : Double)

val csr1 = new CSR("A", 1, 10, 2.1)
val csr2 = new CSR("B", 2, 20, 3.2)
val csr3 = new CSR("C", 3, 30, 9.5)

val csrList = List(csr1 ,csr2 , csr3)

Answer
<tr>
    <th> TOTALs </th>
    <th> @csrList.map(_.ltc).sum </th>
    <th> @csrList.map(_.lti).sum </th>
    <th> @csrList.map(_.lts).sum </th>
</tr>