Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Template Questions /

Two templates for every page


Reply


4 Posts   1655 Views

Avatar
webdev

Community Member, 1 Post

15 March 2010 at 9:14pm

Hi.
I need SS to publish every page in my project into two separate templates - HTML file and JSON file.
For example, if I have a page 'News', I would like to publish it into /news as HTML and /news-json as JSON.
What is the easiest way to do that?

Avatar
banal

Community Member, 901 Posts

15 March 2010 at 10:12pm

Hi

That's rather easy to do.
Just create a separate action in your page controller class, something like this:

public function json(){
   return array();
}

Then you can create a template for this, example: Page_json.ss

This template will then be used, when you call the json action on the controller.. this is as easy as: /pageurl/json

Avatar
banal

Community Member, 901 Posts

15 March 2010 at 10:31pm

There's also another possibility, where you don't even need two different URLs (eg. just /news, instead of /news and /news/json).
You could do that by detecting AJAX requests in your index action and return JSON data if an ajax request was detected.

public function index(){
   // detect ajax request.
   // If it's not an ajax request return array() to render with default template
   if(Director::is_ajax() == false){
      return array();
   }
   
   // populate some data. This is just an example:
   $data = array( 'Title' => $this->Title, 'Content' => $this->Content );
   // return data encoded as json
   return json_encode($data);

}

Director::is_ajax() will automatically detect AJAX requests. To test this, you can also append ?ajax=1 to the URL and see the AJAX output.

Avatar
edk

Community Member, 39 Posts

18 March 2010 at 5:41pm

Edited: 18/03/2010 5:41pm

Hi WebDev,

Banal has you covered here but....If you haven't already I strongly recommend grabbing a copy of the Silverstripe book. [url]http://www.amazon.com/SilverStripe-Complete-Guide-Development-Wiley/dp/0470681837/ref=sr_1_1?ie=UTF8&s=books&qid=1268887245&sr=8-1-spell[/url].

There is a whole section in there on Silverstripe's built in and ready RESTful services. By default it is disabled but it is ready and waiting there to be used. Not sure if it is limited to only DataObjects though, so you may need to look further into that.