CAKEPHP 3: Set a value for the default layout. This becomes undefined when fetching content, why?

时间:2017-04-10 00:25:08

标签: cakephp scope views undefined default

First let me say thanks in advance for your help. I am new to CakePHP framework and I am trying to learn this fast due to a project I’ve been thrown into.

I think my problem might be due to not fully understanding how the views are working. This is how I think it works. (please correct me if I am wrong): The default layout is a template. $this->Fetch() is kind of like ajax where by only the div containing the element is re-rendered/updated?

my basic html default template is:

<!DOCTYPE html>
<html>
<head>
    <?= $this->Html->charset() ?>
    <?= $this->fetch('meta') ?>
    <?= $this->fetch('css') ?>
    <?= $this->fetch('script') ?>
</head>
<body>
<nav class="top-bar expanded" data-topbar role="navigation">
    <ul class="title-area large-3 medium-4 columns">
        <li class="name">
            <h1><a href=""><?= $this->fetch('title') ?></a></h1>
        </li>
    </ul>
    <div class="top-bar-section">
        <?= $this->Element('Navbar/navbar'); ?>
        <?= $this->fetch($navigation); ?>
    </div>
</nav>
<?= $this->Flash->render() ?>
<div class="container clearfix">
    <?= $this->fetch('content') ?>
</div>
</body>
</html>

in the default layout:

<div class="top-bar-section">
    <?= $this->Element('Navbar/navbar'); ?>
    <?= $this->fetch($navigation); ?>
</div>

I set the value of $navigation in my UsersController to:

   $this->set('navigation', 'navbar2');

This calls the element (Element/Navbar/navbar.ctp)

<?php $this->start('navbar2'); ?>
<ul class="nav navbar-nav">
    <li><?= $this->Html->link(__('Session history'), ['controller' => 'Sessions', 'action' => 'index']) ?></li>
</ul>
<?php $this->end(); ?>

the result is (web page view): navbar Which is what I wanted.

However, when I click on Session history from /users/home to /sessions this happens: undefind var

So either two things are happening, somehow the fetch(‘content’) is causing $navigation to fade out of scope and become undefined or I’m completely wrong about $this-fetch() and what is really happening is the whole default page is reloaded fresh.

I guess my first question is, which one is correct? Ajax style fetch content without refreshing the whole page, or is it refreshed every time and $navigation is a completely new variable that has not been assigned.

In either case, how do I set the default layout values that will only change when an event occurs? In my example, navbar2 is for non-admin, while navbar1 is for admin. I only need to check this once when logging in.

0 个答案:

没有答案