1

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>
Markku
  • 555
  • 1
  • 8
  • 15
  • 3
    In scala, last statement of the block treated as return result, in your first case you'll get Unit aka void (result of println) and option is simply thrown away – om-nom-nom Mar 26 '13 at 06:29

2 Answers2

2

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.

korefn
  • 955
  • 6
  • 17
0

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.

2manyprojects
  • 845
  • 7
  • 14
  • I have already realized @for solution works, but I would like to understand how to do this using @{...} closure. Reason for this is that I must write around 10 lines of scala code before for loop. These 10 lines create list, which will be looped. – Markku Mar 28 '13 at 07:18
  • Ok, I see. I'm new to scala, but by the logic above, wouldn't adding the options to a collection using a loop and then mapping the collection to a print statement on the last line of the block work? – 2manyprojects Mar 28 '13 at 12:35
  • I was also thinking about using print statement, but didn't understand how to do that. I am super newbie in Scala. – Markku Apr 02 '13 at 05:10
  • Yeah, me too. The block construct has piqued my interest though, so thanks for introducing me to that. I'm going to play around a bit, and if I get the expected output I'll edit my answer. If you figure it out first ping me, I'd like to see a working approach. – 2manyprojects Apr 02 '13 at 16:02