Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top