【问题标题】:Play scala template syntax for a string播放字符串的 scala 模板语法
【发布时间】:2016-07-27 14:08:58
【问题描述】:

我正在尝试使用 scala 参数驱动此 html 锚标记的 href 属性,但似乎无法使其工作。

@{
    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>
    }    
}

在这两个示例中,href 属性都没有正确生成,但是当我在 html 属性之外的 span 标记中使用 {key} 时,它会正确打印出密钥。

【问题讨论】:

  • 你试过@{key}吗?您在第一个 href 示例中使用了括号,而在第二个示例中没有使用 @

标签: html scala playframework playframework-2.0


【解决方案1】:

Twirl 不支持else-if。由于这给您带来了问题,您将其包装在一个动态块 @{} 中,我认为您可以使用它(从未尝试过)。然而,这不是通常的做法,最好使用模式匹配。

您的代码如下所示:

@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>
    }
}

现在可行,但是您也可以使用 defining(而不是 vals)定义可重复使用的范围值,以减少 p.getKey 和 href 本身的重复:

@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>
            }
        }
    }
}

当假设消息除了键之外都一样时,它变得更容易了,放弃模式匹配和 href 定义(因为它只使用过一次):

@defining(p.getKey()) { key =>
    <a href="/authentication/@key">Sign in with @key</a>
}

【讨论】:

    猜你喜欢
    • 2012-05-11
    • 2011-09-08
    • 2019-02-07
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    相关资源
    最近更新 更多