0

I'd like a Scala condition inside the "class" HTML attribute to be parsed, but the Scala Template isn't playing ball:

@priceTag(amount: Currency) = @{
    <div class='priceTag {if(amount.toDouble == 0.0d) "FREE"}'>
        {if(amount.toDouble > 0.0d) {amount.format("¤#")} else {"FREE"}}
    </div>
}

Yields:

<div class="priceTag {if(amount.toDouble == 0.0d) &quot;FREE&quot;}"> 
    £1
</div>

And I'd like it to yield:

<div class="priceTag"> 
    £1
</div>

Suggestions gratefully appreciated

Chris Beach
  • 4,302
  • 2
  • 31
  • 50
  • 1
    It looks like you're missing some `@` signs (`@{if...}`). I'm surprised the content of the div is `£1` instead of the whole `if` line. – Carsten Feb 11 '13 at 23:20
  • @Carsten thanks for the reply, but unfortunately adding the @ sign there doesn't help. Yields HTML: class="priceTag @{if(amount.toDouble == 0.0d) "FREE"}" – Chris Beach Feb 12 '13 at 12:07
  • Oh, right, I didn't see the second `@` sign in the first line. *writing an answer* – Carsten Feb 12 '13 at 16:09

2 Answers2

2

Your code has several errors. They just hide each other. :-)

Let's go through them:

@priceTag(amount: Currency) = @{ ... }

The @{ ... } construct means that everything inside the curly brackets is a block of Scala code. This doesn't rause an error, because your block,

<div class='priceTag {if(amount.toDouble == 0.0d) "FREE"}'>
    {if(amount.toDouble > 0.0d) {amount.format("¤#")} else {"FREE"}}
</div>

is actually valid Scala code (because of Scala's XML literals). It's just that Scala recognizes priceTag {if(amount.toDouble == 0.0d) "FREE"} as the class name of your div.

What you probably wanted to do is this:

@priceTag(amount: Currency) = {
    <div class='priceTag @{if(amount.toDouble == 0.0d) "FREE"}'>
        @{if(amount.toDouble > 0.0d) amount.format("¤#") else "FREE"}
    </div>
}

Notice the @ signs before the two if blocks. I have also removed the curly brackets around amount.format("¤#") and "FREE". You can keep them of course, if you want, but they're not required.

Carsten
  • 17,991
  • 4
  • 48
  • 53
0

I am beginner in scala but the if statement is not correct to me, I would go with:

@if(amount > 0) {
        <div class="priceTag"> 
           @amount
        </div>
} else {
        <div class="priceTag FREE"> 
           @amount
        </div>
}

Or:

        <div class="priceTag @if(amount == 0) { FREE }"> 
           @amount
        </div>
adis
  • 5,901
  • 7
  • 51
  • 71