Play!Framework‎ > ‎

Play! - How to add format support

In Rails you can request different formats by adding ".format" at the end of the URL.
For example http://www.mograbi.co.il/index.xml will return an XML response and not HTML.

The default is of course - HTML.

How can you add the same behavior in Play!??

The way I do it is by adding the following mappings to conf/routes file.

*       /{controller}/{action}.html                 {controller}.{action}(format:'html')
*       /{controller}/{action}.xml                 {controller}.{action}(format:'xml')
*       /{controller}/{action}.json                 {controller}.{action}(format:'json')


This will simply require a new entry for each format.
If I want to make this generic I can simply write

*       /{controller}/{action}.{format}           {controller}.{action}(format:{format})


Then you can simply query for "request.format".

If you create the following enum :
public enum EFormat {
    html,xml,json
}


You can even use a switch very similar to rails.

Rendering


The easiest way to render so far in rails is to call

render(layout.format, args...)

Which can easily look like
render(Welcome.xml,name)

Comments