CakePHP Extending one View from Another

Published on Sep 20, 2012 by Jamie Munro

A new feature in CakePHP 2.1 is the ability to make one view extend another view.  This is a very neat feature; it's actually quite similar to the concept of Jquery templating.  The concept behind it is relatively straight forward.  You define one view that contains common elements that will be updated in another view.  The goal is to avoid duplicating the HTML in a different view.


 The best way to learn a new technique is to review an example.  Let's explore by creating a common header file that other views can extend from and alter as required.  Create a new file in app/View/Common/header.ctp:


<header>
<nav>
<?php echo $this->fetch('menu'); ?>
</nav>
<div id="breadcrumb">
<?php echo $this->fetch('breadcrumb'); ?>
</div>
</header>

<h1><?php echo $this->fetch('title'); ?></h1>
<?php echo $this->fetch('content'); ?>


The key elements in this common view file are the various different $this->fetch() function calls.  When I create a new view file that extends this one, it is expected that the new view will fill in this data.  That will allow me to create a different menu, breadcrumb, and title.  Anything else will be displayed in the "catch all" content tag.

Now that I've created a common view, I need to create a new view that will extend this view and fill in the areas defined above.  Create a new file in app/View/<controller>/<view>.ctp (be sure to replace controller and view with where you would like this code to be executed):


<?php
$this->extend('/Common/header');

$this->assign('title', $title);
$this->assign('breadcrumb', 'Home > User > View');

$this->start('menu');
?>
<li><?php echo $this->Html->link('Home', array('action' => 'index', 'controller' => 'home')); ?></li>
<li><?php echo $this->Html->link('Profile', array('action' => 'view', 'controller' => 'user')); ?></li>
<li><?php echo $this->Html->link('Edit Profile', array('action' => 'edit', , 'controller' => 'user')); ?></li>
<li><?php echo $this->Html->link('Logout', array('action' => 'logout', , 'controller' => 'user')); ?></li>
<?php $this->end(); ?>

<?php
// Display the remaining content
...


The key pieces of code that make this work are the $this->extend() function that tells CakePHP which view that it is extended.  Next there is the option to either simply assign a value or start and end a value depending on whether your code will fit on one line of code or multiple.

That's it!  Now you can easily create other views that extend this view as well and simply fill in a new menu, breadcrumb, and title.

Tags: CakePHP | view | extend

Related Posts

blog comments powered by Disqus