Cody CMS
Fork me on GitHub

Change the view

Q: How do I change the default view as defined by the template in my controller?

A: doRequest of a Controller receives a function to be called when you're done with everything you wanted to do before rendering. There are a number of different parameters options that can be given to this function that influence the behaviour for rendering the html page.

  • if you call the "finish" function with no parameters
    • the view specified in the template will be used
    • but you can change the view by altering the fn property in the current content. 
      Ex:  context.fn = "other-view.ejs"; 
  • if you call the function with a String parameter, Cody assumes you are specifying a different file to be used for rendering
    • if this string start with "-/", then Cody looks in the standard cody views in its own directory
    • all other strings should be rendering templates with your "view" directory (or a sub directory of it)
  • if you call the function with an object as parameter it will be passed to the controller.gen function, along with an optional header. Below also the code of the "gen" function.
    • If no header is passed, Cody assumes "application/json" as content type
    • If the content passed is an object, Cody will apply JSON.stringify to it and send it to the browser. This is handy for handling Ajax calls.
    • String are passed straight to the browser. So you can stringify your own data or send something different... html, xml, plain text, binary data, excel files, ... you name it.

See the code from the Application engine:

 controller.doRequest( function(fn, header) {
    // callback function should always be called by doRequest
    //  render with the specified or the template in the context 
// (controller may have changed it with context.fn = "..." ) // if no render template present ( == "") either // -- assume the controller performed res.writeHead() / .write() / .end() -- ajax req? // -- another controller has taken over if (typeof fn === "object") { controller.gen(fn, header); } else { if (typeof fn !== "undefined") { context.fn = fn; } self.log("Application.handToController -> finished -> render view", (context.fn==="") ? "** none **" : context.fn); self.renderView( context ); } controller.close(); });

 

The Controller.gen function.

 Controller.prototype.gen = function( theContent, theHeader ) {
  if (typeof theHeader === "undefined") {
    this.context.res.writeHead(200, { "Content-Type": "application/json" });
  } else {
    this.context.res.writeHead(200, theHeader);
  }

  if (typeof theContent !== "string") {
    this.context.res.write(JSON.stringify(theContent));
  } else {
    this.context.res.write(theContent);
  }
  this.context.res.end();
};