How to pass a script to main.scala.html - Play! 2

我的梦境 提交于 2019-12-20 02:57:15

问题


I am trying to pass javascripts specific to a page as a parameter to the main template. This is what I have tried:

main.scala.html:

@(title: String,moreScripts: Html)(content: Html)

<!DOCTYPE html>

<html>
    <head>
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
        <script src="@routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
        @moreScripts
    </head>
    <body>
        @content
    </body>
</html>

test.scala.html:

@main("Test",<script src="javascripts/test/test.js" type="text/javascript"></script>) {
        <h1>Test</h1>
}

But I am getting an type mismatch; found : scala.xml.Elem required: play.api.templates.Html error. I also tried wrapping the <script> statement in @{} to no avail.

How do I need to structure the <script> statement so that it is recognises the statement as HTML?


回答1:


This has been discussed on the mailing list. Hope that helps.

@main{ <script src="javascripts/test/test.js" type="text/javascript"></script> } {
   <h1>Test</h1>
}



回答2:


I struggled with this as well, but this seemed to work for me:

main.scala.html:

@(title: String, moreScripts: Html = Html(""))(content: Html)
<!DOCTYPE html>
<html>
  <head>
   <title>@title</title>
   @moreScripts
  </head>
  <body>
   @content
  </body>
</html>

test.scala.html:

@moreScripts = { <script src="routes.Assets.at("javascripts/MyJS.js")"></script>}

@main("Page Title", moreScripts) {
  <h1>Some content here</h1>
}

Of course, your Javascript file should be located at app/assets/javascripts as either a standard Javascript or Coffeescript file



来源:https://stackoverflow.com/questions/10826906/how-to-pass-a-script-to-main-scala-html-play-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!