Jump to:

3393 Posts in 976 Topics by 852 members

Template Questions

SilverStripe Forums » Template Questions » Two templates for every page

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

Page: 1
Go to End
Author Topic: 1547 Views
  • webdev
    Avatar
    Community Member
    1 Post

    Two templates for every page Link to this post

    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?

  • banal
    Avatar
    Community Member
    901 Posts

    Re: Two templates for every page Link to this post

    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

  • banal
    Avatar
    Community Member
    901 Posts

    Re: Two templates for every page Link to this post

    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.

  • edk
    Avatar
    Community Member
    39 Posts

    Re: Two templates for every page Link to this post

    Hi WebDev,

    Banal has you covered here but....If you haven't already I strongly recommend grabbing a copy of the Silverstripe book. 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.

    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.

    1547 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.