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

2019-02-26 09:18发布

问题:

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