Jul 28, 2011

Use GreenScript correctly

I've just encountered an mail about greenscript in the playframework google group. Here is the code:

-- main.html --


<html>
<head>
#{get 'title' /}
#{get 'moreStyles' /}

#{script 'jquery-1.6.2.min.js' /}
#{script 'jquery.validate.min.js' /}
#{script 'jquery.form.js' /}
#{get 'moreScripts' /}
</head>
<body>
#{doLayout /}
</body>
</html>

-- index.html --

#{extends 'main.html' /}
#{set title:'title' /}
#{set 'moreStyles'}
#{greenscript.css "main005", output:'all'/}
#{/set}
#{set 'moreScripts'}
#{greenscript.js output:true}
#{/set}
...


So what's wrong in the above code:
1. JavaScripts did not get processed (minimize and compress) at all. The above code is still using #{script} tag to output JavaScripts, which will NOT gain the benefit of greenscript at all
2. Using #{set 'moreScripts'} and #{get 'moreScripts'} is neither needed nor encouraged when you have the power of greenscript.

This code gives me a feeling that you have an electric motor saw but you are using it like a plain saw by not powering it on. The correct way could be much more simpler:

-- main.html --
<html>
<head>
#{get 'title' /}


#{greenscript.js 'jquery.form < jquery.validate.min < jquery-1.6.2', output:'all'/}
#{greenscript.css output:'all'/}
</head>
<body>
#{doLayout /}
</body>
</html>

-- index.html --

#{extends 'main.html' /}
#{set title:'title' /}
#{greenscript.css 'main005' /}

Tips:
  • you can declare multiple resource files in one greenscript tag. E.g. #{greenscript.js 'a b c'/} declares /public/javascripts/a.js, /public/javascripts/b.js and /public/javascripts/c.js using one call to greenscript js tag
  • you can declare dependencies inside greenscript tag, e.g. #{greenscript.js 'jquery.validate.min < jquery-1.6.2' /} will guarantee jquery-1.6.2.js be rendered before jquery.validate.min.js/
  • use [output: 'all'] to render all declared and not rendered resources. E.g. #{greenscript.css output: 'all' /} will output all declared css resource in place. Usually you should use [output: 'all' ] inside <head> block
  • By typing "play greenscript:cp -a ." in your project folder, you copied the needed tags to your project and you can simply the invoking of greenscript tag as: #{js .../}, #{css ... /}

No comments: