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 /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Two templates for every page

Go to End

4 Posts   2139 Views


Community Member, 1 Post

15 March 2010 at 9:14pm

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?


Community Member, 904 Posts

15 March 2010 at 10:12pm


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:

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


Community Member, 904 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.


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.

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.