How to use scala and html code inside single block

2019-09-05 22:17发布

问题:

why option html element is not binded inside select in case 1?

Case 1: not work

@base{
  <select name="" value="" class="custom-select">
  @{
    println("1"); // this is printed to console             
    <option value="test">i</option> // this is not shown in html
    println("2"); // this is printed to console                     
  }
  </select>
}

Case 2: work

@base{
  <select name="" value="" class="custom-select">
  @{
    println("1"); // this is printed to console             
    <option value="test">i</option> // this is shown in html                    
  }
  </select>
}

Update:

How one can create a loop which binds all option elements to scala template? Following code does not bind any option elements. What is actually return type? Empty line?

<select name="" value="" class="custom-select">
@{
    for(i <- 1 to 10) {
        <option value="@i">@i</option>
    }
}
</select>

回答1:

The code block @{...} is a closure that has an inferred return type from the last statement.

In the first case the return type is inferred to be Unit since the println(...) returns Unit

In the second block the html is returned.



回答2:

I can't speak to the first question directly, but assuming that @korefn and @om-nom-nom are correct; that the block is a closure and is interpreting the return as a void.

In response to your update, I would try:

@for(i <- 1 to 10) {
    <option value="@i">@i</option>
}

which is how I've used it in the past. I've also found it helpful to use a nested @if block to handle the selected option differently so that it is selected on loading the document.