CodeIgniter Forums
Conditional layout templates - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: Conditional layout templates (/showthread.php?tid=77352)



Conditional layout templates - legon614 - 08-20-2020

I want to use layout templates instead of doing this:

PHP Code:
            echo view('html_top'$vars);
            echo view($view$vars);
            echo view('html_bottom'$vars); 

The think is - my application handles views differently if they are AJAX calls or not. If they are AJAX it returns a JSON with the view inside of it. If not, it will return the view with top html and bottom html. For this to work I have created a View library, like so:

PHP Code:
    public function view($view$vars = array())
    {
        $request service('request');
        $siteConfig config('Site');
        $session service('session');

        $page_title $this->url_to_title($vars);

        if ($request->isAJAX()) {
            if (isset($vars['json'])) {
                $data['manipulateDom'] = $vars['json'];
            }

            $data['title'] = $page_title;

            $vars['logged_in']  $session->logged_in;
            $vars['site_name'] = $siteConfig->name;
            $data['content'] = view($view$vars);

            echo json_encode($data);
        } else {
            $vars['page_title'] = $page_title;
            $vars['logged_in']  $session->logged_in;
            $vars['site_name'] = $siteConfig->name;
            
            
echo view('html_top'$vars);
            echo view($view$vars);
            echo view('html_bottom'$vars);
        }
    

But view templates are not triggered from the controller, but from the view. Is there any way of echoing a template in a controller with another view inside of it? I guess I can pass $request->isAJAX() to the view and do something like this:

PHP Code:
<?php if ($isAJAX): ?>
<?= $this
->extend('default'?>
<?php 
endif; ?>

But it doesn't feel right, and I would then have to put it in all views. I rather do it from the controller or a lib.


RE: Conditional layout templates - includebeer - 08-20-2020

Your template can use include() to render the main content, and for your ajax call you can return only this view. See https://codeigniter4.github.io/userguide/outgoing/view_layouts.html#including-view-partials

PHP Code:
<?= $this->extend('default'?>

<?= $this->section('content'?>
    <?= $this->include('main_content'?>
<?= $this
->endSection() ?>



RE: Conditional layout templates - InsiteFX - 08-21-2020

You can also echo a view in a view.