I am trying to drive the href attribute of this html anchor tag using a scala parameter and can't seem to get it to work.
@{
val key = p.getKey()
if(key == "facebook") {
<a href="/authenticate/@(key)">Sign in with facebook</a>
} else if (key == "twitter"){
<a href="/authenticate/{key}">
<span>Sign in with twitter {key} (this works)</span>
</a>
}
}
In both examples the href attribute is not generating properly, but when I use {key} in the span tag that is outside of the html attribute, it prints out the key properly.
Twirl doesn't have support for else-if. Since that caused you problems you wrapped it in a dynamic block @{}
, which you can make work I think (never tried it). However this is not how things are usually done, it's preferred to use pattern matching instead.
Here is how your code could look like:
@p.getKey() match {
case "facebook" => {
<a href="/authenticate/@{p.getKey()}">Sign in with facebook</a>
}
case "twitter" => {
<a href="/authenticate/@{p.getKey()}">
<span>Sign in with twitter - key @{p.getKey()} </span>
</a>
}
}
Now that works, however you can also define reusable scoped values with defining (instead of vals) to cut down on the duplication of p.getKey
and the href itself:
@defining(p.getKey()) { key =>
@defining(s"/authentication/$key") { href =>
@key match {
case "facebook" => {
<a href="@href">Sign in with facebook</a>
}
case "twitter" => {
<a href="@href"> <span>Sign in with twitter - key @key</span> </a>
}
}
}
}
When assuming that the message is all the same except for the key it gets even easier, scrap the pattern matching and the href defining (since its used just once):
@defining(p.getKey()) { key =>
<a href="/authentication/@key">Sign in with @key</a>
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments