gpt4 book ai didi

java - 如何将 Scala 变量注入(inject) Scala 模板 HTML 中的 html 属性(字符串)

转载 作者:太空宇宙 更新时间:2023-11-04 13:24:53 26 4
gpt4 key购买 nike

让我解释一下我的要求。目前我们使用 Scala 模板,它有一些 html 代码和 Scala 属性。

示例test.scala.html

@(hostName: String, token: String, protocol: String, supportEmail: String)
@import helper._
<!DOCTYPE html>

<html>
<head>
<title></title>
</head>
<table>
<tr>
<td>&nbsp;</td>
<td style="color: #626262;">
<p style="font-size:14px;">
<br/>
Our app will let you access your company intranet.<br/><br/>
Your activation code is <b>@token</b><br/><br/>

If you have any questions, please contact our <a href="mailto:@supportEmail">support team</a> anytime.
<br/><br/>
Best regards,<br/>
The Support Team
</p>
</td>
</tr>
</table>
</body>

如果您看到上面的代码 @token@supportEmail 是动态的,我们将传递给 Scala。

到目前为止看起来还不错。需求发生变化,客户现在希望我们从数据库中读取内容。他们想要保存实际的 html 内容(表...表尾)。

所以我获取了代码并将其存储在数据库列中。我可以使用 @Html 将此内容传递到我的 View 函数。

现在我的新 Scala View 函数如下所示:

@(hostName: String, token:String, protocol: String, supportEmail: String, content: String)
@import helper._
<!DOCTYPE html>

<html>
<head>
<title></title>
</head>
@Html(content)

但是我无法动态传递@token@supportEmail。它被视为普通字符串。渲染后如下所示:

Our app will let you access your company intranet, files and SaaS services from your device.

Your activation code is @token

If you have any questions, please contact our support team @supportEmail anytime.

Best regards,
The support Team

谁能解释一下@Html出了什么问题,我可以解析动态内容吗?如果没有还有什么替代方案。

最佳答案

@Html函数允许您从变量插入 HTML 片段,而无需转义特殊字符,例如 <> 。但是,它仅适用于静态 HTML,不幸的是,它无法解析其中的其他 Scala 代码。

就您的情况而言,实现您的要求的最简单方法是在将内容传递到 View 之前在 Controller 中准备内容。 Controller 方法中的代码或多或少看起来像这样:

public Result showContent() {
//fetching all your data here
content = content.replace("@token", token);
content = content.replace("@supportEmail", supportEmail);
return ok(views.html.test.render(hostName, protocol, content));
}

基本上,您不必在表格内容中使用 Twirl 占位符。如何在内容中标记可替换参数由您决定。只需确保 replace来电符合您的模式。

我假设tokensupportEmail未在 View 的其他地方使用,因此我将它们从 View 的标题中删除。

@(hostName: String, protocol: String, content: String)

简单的解决方案通常是最好的解决方案:)

关于java - 如何将 Scala 变量注入(inject) Scala 模板 HTML 中的 html 属性(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32761791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com