How to use scala and html code inside single block

◇◆丶佛笑我妖孽 提交于 2019-12-12 01:35:22

问题


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.



来源:https://stackoverflow.com/questions/15630690/how-to-use-scala-and-html-code-inside-single-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!