我想将 javascript 添加到 <head>
我的网页从标签内。
这是我在我的页面上使用的 moreScripts 等价物:
main.scala.html
@(title: String, scripts: Html = Html(""))(content: Html)
<!DOCTYPE html>
<html lang="nl">
<head>
<title>@title</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
@scripts
</head>
<body>
@content
</body>
</html>
page.scala.html
@scripts = {
<script type="text/javascript">
$(document).ready(function() {
alert(1);
});
</script>
}
@main("Title", scripts) {
<p>page content</p>
}
到目前为止一切顺利!但是,我想在我编写的标签(组件)中执行相同的操作,该标签需要在网页中包含一些 javascript 代码。
我的问题是如何传递 <script>
从标签到 main.scala.html
的元素?
所以 page.scala.html
会是:
page.scala.html
@import tags._
@main("Title") {
@mytag("green")
}
mytag.scala.html
@(color: String)
<script type="text/javascript">
$(document).ready(function() {
alert('@color');
});
</script>
<p>Some more content</p>
在本例中为 <script>
标记在 HTML 页面中途呈现,我想传递 <script>
标记到 @scripts
变量,以便它可以在 <head>
中呈现标签。
最佳答案
好的,恕我直言,我想出了一个更好的解决方案。
我创建了以下标签:
script.scala.html
@(content: Html)
@{
var additionalScripts = ctx().args.get("additionalScripts").asInstanceOf[List[Html]];
if(additionalScripts == null) {
additionalScripts = new ArrayList[Html]();
ctx().args.put("additionalScripts", additionalScripts)
}
val added = additionalScripts.add(content);
}
renderscripts.scala.html
@additionalScripts = @{ctx().args.get("additionalScripts").asInstanceOf[List[Html]]}
@if(additionalScripts != null) {
@for(additionalScript <- additionalScripts) {
@additionalScript
}
}
在您的 main.scala.html
中,您可以使用:
@(title: String)(content: Html)
@import tags._
<!DOCTYPE html>
<html lang="nl">
<head>
<title>@title</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
@renderscripts()
</head>
<body>
@content
</body>
</html>
您可以使用以下方法在您的模板或标签中指定额外的脚本:
@import tags._
@script {
<script type="text/javascript">
$(document).ready(function() {
alert('This will be in the head!');
});
</script>
}
这很好,对吧? :)
也许有人可以使用他们的 Scala 魔法清理或增强我的代码:)
关于java - 将 <script> 添加到 <head> from Play Framework 2 中的 scala 模板标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18737876/