mane
mane

Reputation: 1179

How to specify, different JS file for different view page in play framework?

How do we define different javascript files for different view pages in play framework??

One way is to=>

@main(title, """
@*JS CODE*@
"""{
//Template Codes
}

And in main template, use it like=>

@(title,stringJS){
<script>
@Html(stringJS)
</script>
}

But what if the JS code is to be used in not all pages but selected few, the dev can't copy the JS code in every relative view page.In my case all the javascripts are loaded on the footer, which is a seperate template.

How do we solve this problem??

Any help is appreciated, thank you!

Upvotes: 0

Views: 72

Answers (2)

biesior
biesior

Reputation: 55798

It's described in the Common templates use cases doc , section : 'moreScripts and moreStyles equivalents'

In very short it works like this (view)

@moreScripts = {
    <script type="text/javascript">alert("hello !");</script>
}

@moreStyles = {
    <style>background: pink;</style>
}


@main("Title", moreScripts, moreStyles){

   Html content here ...

}

and in main.scala.html start with:

@(title: String, moreScripts: Html = Html(""), moreStyles: Html = Html(""))(content: Html)

<!DOCTYPE html>

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

Upvotes: 2

mane
mane

Reputation: 1179

I came up with my solution,thanks to this Helpful SO post, what I did was:

@main(title, """
@*NO JS CODE, but declaration itself*@
<script src="/assets/javascripts/libs/main.js" type="text/javascript"></script>
<script src="@routes.Assets.at("javascripts/libs/main.js")" type="text/javascript"></script>//Doing this gives out errors, so I had to hardcode the "src" location
"""{
//Template Codes
}

If there is more efficient way to solve this issue, ideas are welcome, because hard-coding src isn't an efficient way of dealing with this issue, imo.

Upvotes: 0

Related Questions