Search code examples
htmlscalahtml-tablescala.jsscalatags

Add table row after creating table body using scalatags


Using scalatags, normally I create a table like this:

table(
  thead(
    tr(
      th("A"),
      th("B")
    )
  ),
  tbody(
   tr(
    td("HELLO"),
    td("WORLD")
   ),
   tr(
    td("FOO"),
    td("BAR")
   )
  )
)

Is it also possible to add tr elements after the table has been declared? Something like this would be great:

val myTableBody = tbody(
   tr(
    td("HELLO"),
    td("WORLD")
   )
)

table(
  thead(
    tr(
      th("A"),
      th("B")
    )
  ),
  myTableBody
)

if(myCondition){
  myTableBody.addTr( // this is what I am searching for
   tr(
    td("FOO"),
    td("BAR")
   )
  )
}

*edit: For clarification, at the moment I am doing something like this:

table(
  thead(
    tr(
      th("A"),
      th("B")
    )
  ),
  tbody(
   tr(
    td("HELLO"),
    td("WORLD")
   ),
   if(myCondition){
    tr(
     td("FOO"),
     td("BAR")
    )
   } else {
    tr() // this is a bit ugly
   }
  )
)

Solution

  • It can certainly be done, but has nothing to do with Scalatags per se. This is pretty normal DOM manipulation, and you need a library or framework for working with that. It can be done in raw DOM, but it's more common to develop web applications using frameworks such as React, or at least libraries such as jQuery. There are zillions of such options (including a somewhat rough Scalatags-based on I built myself); you should choose which one best suits your needs...