Rendering and not rendering


July 28, 2007
One of the most common questions I see on IRC is "How do I stop the view from displaying?". <br/> <br/>The controller has a handy little attribute <em>autoRender</em>, setting it to false will stop the view from being displayed. <br/> <br/>Also using the <em>render(...)</em> method automatically sets autoRender to false. This is handy if you want to another view aside from the default one for an action. <br/> <br/>Some example code: <br/><div class="code"><pre><span class="cp">&lt;?php</span> <span class="c">// in a controllers action</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">autoRender</span> <span class="o">=</span> <span class="k">false</span><span class="p">;</span> <span class="nf">header</span><span class="p">(</span><span class="s1">&#39;Content-type: application/pdf&#39;</span><span class="p">);</span> <span class="nf">readfile</span><span class="p">(</span><span class="s1">&#39;/path/tp/pdf_file&#39;</span><span class="p">);</span> <span class="c">// or say you want to render an element as a view. </span> <span class="c">// maybe you are using ajax</span> <span class="k">if</span><span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">RequestHandler</span><span class="o">-&gt;</span><span class="na">isAjax</span><span class="p">())</span> <span class="p">{</span> <span class="c">// is a cake component</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">viewPath</span> <span class="o">=</span> <span class="s1">&#39;elements&#39;</span><span class="o">.</span><span class="nx">DS</span><span class="o">.</span><span class="s1">&#39;products&#39;</span><span class="p">;</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">render</span><span class="p">(</span><span class="s1">&#39;product_table&#39;</span><span class="p">,</span> <span class="s1">&#39;ajax&#39;</span><span class="p">);</span> <span class="p">}</span> <span class="cp">?&gt;</span><span class="x"></span> </pre></div> <div style='display:none'>&lt;?php <br/> <br/>// in a controllers action <br/>$this-&gt;autoRender = false; <br/>header('Content-type: application/pdf'); <br/>readfile('/path/tp/pdf_file'); <br/> <br/>// or say you want to render an element as a view. <br/>// maybe you are using ajax <br/>if($this-&gt;RequestHandler-&gt;isAjax()) { // is a cake component <br/> $this-&gt;viewPath = 'elements'.DS.'products'; <br/> $this-&gt;render('product_table', 'ajax'); <br/>} <br/> <br/>?&gt;</div> <br/> <br/>Some links: <br/><a href="http://api.cakephp.org/1.2/class_controller.html#90046e6b62c91452a987c9573372c2ac">Controller::render</a> [api.cakephp.org] <br/><a href="http://api.cakephp.org/1.2/class_request_handler_component.html">RequestHandler</a> [api.cakephp.org] <br/> <br/>-rtconner