Search code examples
javacsstomcatplayframeworkhref

Java/Play - Proper way to link to CSS/JS?


I'm creating a Play! 2.1.1 application which I have packaged into a war file using Play2War. This required me to add a context, application.context=/theApp/, in the application.conf file.

I deployed the WAR file to a tomcat7 server which resulted in the url localhost:8080/theApp/.

CSS/JS files load when the url is for example http://localhost:8080/theApp/thisseemstowork, but once the url is http://localhost:8080/theApp/thisoughttowork/180 none of the CSS/JS files are loaded. I simply get

GET http://localhost:8080/theApp/thisoughttowork/public/javascripts/vendor/bootstrap.min.js 404 (Not Found) 

This is how I link to the js file in the views:

    <script src="public/javascripts/vendor/bootstrap.min.js"></script>

This is in my routes file

GET     /public/*file               controllers.Assets.at(path="/public", file)

Anyone have an idea what I'm doing wrong? Let me know if you need any more info.


Solution

  • You need to use the Assets controller and reverse-routing.

    <script src="@routes.Assets.at("javascripts/vendor/bootstrap.min.js")"></script>
    

    This will generate the correct path no matter where you are in the app. As you can see from the routes file snippet you posted the path is relative to the /public folder, so this will work for any stylesheets, images, etc you put in there.

    <link rel="stylesheet" href="@Assets.at("stylesheets/bootstrap.min.css")">
    <link rel="stylesheet" href="@Assets.at("other/folder/styles.css")">
    

    Here's Play's documentation:

    http://www.playframework.com/documentation/2.1.1/Assets