Take advantage of assets conventions in Play

It is usual when you are working with Play use this kind of code to refer public assets.

   <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/style.css")"/>
   <script src="@routes.Assets.at("javascripts/jquery-1.4.4.min.js")" type="text/javascript">
   <img src="@routes.Assets.at("images/someimage.png"/>

But, Why do you have to write the name of css, javascript and images folder all the time if they are the convention? When you are using a framework is important to take advantage of all things, in order to avoid silly mistakes, like write the wrong name of the folder. For example, at least to me, it would be better if we could write something like this:

   <link rel="stylesheet" href="@Css("bootstrap.min.css")">
   <script type="text/javascript" src="@Js("main.js")"></script>
   <img src="@Image("someimage.png"/>

To achieve this we just have to use the built in controller named Assets. Let’s see the implementation:

  package helpers

  import controllers.routes

  object AssetsHelper {

    object Css {
	  def apply(file:String) = routes.Assets.at("stylesheets/"+file)

    object Js {
	  def apply(file:String) = routes.Assets.at("javascripts/"+file)

    object Image {
	  def apply(file:String) = routes.Assets.at("images/"+file)


Now, you just have to import this class to all templates. Change your build.sbt and add this line.

   templatesImport ++= Seq("helpers.AssetsHelper._")

If you want to keep update with a lot of Play tips, follow me here and in my twitter :). Also I have my book available in Leanpub, still only in Portuguese and ASAP in English.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s