ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

Scala(Template)のif文をOneLinerで記載したときにハマった

スポンサードリンク

要望。DBに登録されている料金を出力したい

ほい

@* db は、Controllerから取得したObject *@
料金:@{db.price} 円

追加要望 とある料金を出力したいだけだったが、ユーザーによっては利用・利用しないってことがあった

なので、条件分岐を用意してあげた。ほい

料金:@if(db.isUse) { @{db.price} 円 } else { 利用しません }

追加要望 料金にカンマ区切りを追加してほしい

ほいさ。

料金:@if(db.isUse) { @{db.price.toString().reverse.sliding(3,3).map( x => x.reverse).toList.reverse.mkString(",")} 円 } else { 利用しません }

エラーが発生いたしました。

Not parsed?

よくわからへん。。。。(´・ω・)?

とりあえず、改行してみることにした

料金:@if(db.isUse) {
    @{db.price.toString().reverse.sliding(3,3).map( x => x.reverse).toList.reverse.mkString(",")} 円
} else {
    利用しません
}

これだとエラーはでない。しかし、、、

料金:
   利用しません

結果が改行されて出力される....! `;:゙;`;・(゚ε゚ )ブッ!!

色々試行錯誤

ifの「{}」を無くしてみる

料金:@if(db.isUse) @{db.price.toString().reverse.sliding(3,3).map( x => x.reverse).toList.reverse.mkString(",")} 円 else 利用しません

エラー。

illegal start of simple expression

ifを「()」で囲めとのお告げがあった。

料金:@(if(db.isUse) @{db.price.toString().reverse.sliding(3,3).map( x => x.reverse).toList.reverse.mkString(",")} 円 else 利用しません)

エラー

Invalid literal number

よくわからん。。。。とりあえず、文字列をHtml("")で囲ってみる

料金:@(if(db.isUse) @db.price.toString().reverse.sliding(3,3).map( x => x.reverse).toList.reverse.mkString(",") + Html("円") else Html("利用しません"))

エラー

type mismatch; found   : Integer required: String

なるほど。StringとIntegerは演算できねぇよってことですね。

料金:@(if(db.isUse) @db.price.toString().reverse.sliding(3,3).map( x => x.reverse).toList.reverse.mkString(",").toString() + Html("円") else Html("利用しません"))

エラー

')' expected but '@' found.

よくわからん。。。。。(´;ω;`)ブワッ

どうやら、@()の中では@はいらないもよう

料金:@(if(db.isUse) db.price.toString().reverse.sliding(3,3).map( x => x.reverse).toList.reverse.mkString(",").toString() + Html("円") else Html("利用しません"))

すると。。。できた!

いまいちよくわかりまてん(^q^)だうー

構文なのかな。。。とりあえずまとめておく。