Welcome Guest, Not a member yet? Register   Sign In
Conditional layout templates
#1

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.
Reply
#2

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...w-partials

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

<?= $this->section('content'?>
    <?= $this->include('main_content'?>
<?= $this
->endSection() ?>
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
Reply
#3

You can also echo a view in a view.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB