Search code examples
playframework-2.2

Add javascript to current view


Is there a way to add a script tag declared in view B to the list of scripts in view A (which calls B)? The example below should make it clear what I need. I have a base template A:

<html>
    <head>
        <title>@title</title>
        <!-- declared stylesheets -->

    </head>
    <body>
        @content

        <!-- Java script dependencies -->
        <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    </body>
</html>

Note that the base view declares dependencies to jquery.js and bootstrap.js at the end of the file. This is OK except for the following case:

@base(title) {
@header()
@navigation()
<div class="container">
    @content
</div>}

The navigation view has a script tag that depends on jquery already being loaded. When I load the page I get an error stating that "$ symbol is not defined" which makes sense because the script is parsed before jquery is loaded. Is there a way for me to add the script declared in navigation at the end of the base view (after the declaration of jquery)?

I've tried moving the dependency to jquery to the <head></head> section and everything works as expected, but I would like to keep the current layout.

Edit: To be more clear, I want to send the script dependencies from @navigation view to @base view .


Solution

  • Take a look to Play's doc for moreScripts and moreStyles equivalents (last section in doc)

    De dacto it deosn't need to be named scripts so you can use your own name, also you can use it for sending other blocks of HTML into higher level view (layout).

    See answers to similar quesion

    So it can be i.e.:

    @navigationScripts = {
        <script src="/assets/my-navigation.js"></script>
    }
    
    @base(title, navigationScripts) {
        @header()
        @navigation()
        <div class="container">
            @content
        </div>
    }
    

    And in layout:

    @(title: String, navigationScripts: Html = null)
    <html>
        <head>
            <title>@title</title>
            <!-- declared stylesheets -->
    
        </head>
        <body>
            @content
    
    
            <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
            <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
            @navigationScripts
        </body>
    </html>