LordZardeck
LordZardeck

Reputation: 8283

how to properly define two similar layouts for cakephp

I'm using CakePHP 2.2.4 and have similar layouts. For one page, however, the <head> content is the same, but essentially the whole body is different. What I have is a website with a navbar used from twitter's bootstrap. On this one page, the navbar is completely different. I know the quick fix would be to create a layout for just that page, but what if I come across another page I need to make with a different navbar? What would be the "proper" MVC way of doing this?

Upvotes: 0

Views: 649

Answers (2)

kaklon
kaklon

Reputation: 2432

I guess it depends how complex the differences are.

One way to go would be to have a common layout file

   // in app/View/Common/layout.ctp

    <!DOCTYPE html>
    <html lang="en">
    <head>

<!-- Your header content -->

</head>

<body>

    <div id="wrap">
        <div class="navbar">
            <?php echo $this->fetch('menu'); ?>
        </div>
        <div class="container">
            <?php echo $this->fetch('content'); ?>
        </div>
    </div>

    <div id="footer">
        <?php echo $this->fetch('footer'); ?>
    </div>

  </body>
</html>

Have your layout file extending it

//app/View/Layouts/default.ctp
<?php 
$this->extend('/Common/layout');
$this->assign('menu', $this->element('menu'));
echo $this->fetch('content');
$this->assign('footer', $this->element('footer'));
?>

Upvotes: 2

Happy
Happy

Reputation: 826

If every view will have a navbar of some kind, then you can just use CakePHP Elements to display the bar, you would put the element call in your one layout file and set a variable from the controller which you pass to the element to show a specific element...

echo $this->element('navbar', array(
    "which_element" => "thisone"
));

In the above example, your navbar.ctp would have to contain all navbars and use a PHP Switch statement or something to work out which to display based on the $which_element...

Or better still, just call the element directly using the variable from the controller

$this->set('navbar', "thisone"); // this line is in your controller and sets the file name of your nav bar, minus the .ctp extension

echo $this->element($navbar); //this line is in your layout.ctp and renders elements/thisone.ctp, in the above example.

If some pages will have a nav bar but some will not, use View Blocks

$this->start('navbar');
echo $this->element($navbar);
$this->end();

Upvotes: 2

Related Questions