Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Set template from within a controller
  • Hi, I want a way to change the template depending on the page being requested. Is it possible to set a new template file from an extended controller of class controller_template or controller_layout? app/classes/controller/layout.php
    <?php
    class Controller_Layout extends Controller_Template
    {
            public $template = 'layout/layout_old';
    
            public function before($data = null)
            {
                    parent::before();
                    #$this->auto_render = false;
            }
    }
    

    app/classes/controller/home.php
    <?php
    class Controller_Main extends Controller_Layout
    {
            public function action_index()
            {
                    $this->template->template = 'layout/layout_new';
                    return Response::forge($this->template);
            }
    }
    
    Thanks,
  • Yes, you can, but not this way. The Controller_Template() processes the $template property in it's before() method, so by the time your action is called, the template view is already loaded ($this->template will contain a view object). But nobody's stopping you from using:
    <?php
    
    class Controller_Main extends Controller_Layout
    {
        public function action_index()
        {
            $this->template  = \View::forge('layout/layout_new');
        }
    }
    

    With Controller_Template, there is no need to return a response, this will be handed by the after() method, using whatever is set in $this->template. In this case you will need to have a default template, as the after() method only does it's work if auto_render is true. If you don't have a default value and you need to set auto_render to false, your action must return a Response object. Alternatively, set auto_render to false in your before(), call the parent, and set it to true again.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion