Skip to content

Instantly share code, notes, and snippets.

@chrisyour
Created August 25, 2009 23:47
Show Gist options
  • Save chrisyour/175140 to your computer and use it in GitHub Desktop.
Save chrisyour/175140 to your computer and use it in GitHub Desktop.
// CakePHP Block Helper
// Ever wanted a clean way to capture a block of HTML in your CakePHP view and use it later in your layout just like CakePHP uses $content_for_layout?
// I use Rails all the time and take content_for for granted. I recently started a CakePHP project and noticed the absence of a simple content_for method to capture a block of HTML.
// For this example we are creating a helper named $cake, a controller named 'main', and using a layout named 'app'.
// HELPER:
// app/views/helpers/cake.php
<?
/**
* CakeHelper Class
*
* @author Chris Your
*/
class CakeHelper extends AppHelper {
/**
* Begin capturing a block of HTML content
*
* @author Chris Your
*/
function capture(){
ob_start();
}
/**
* Set the captured block of HTML content to a $variable
*
* @param string $variable Assigned name
* @return void
* @author Chris Your
*/
function content_for($variable){
$view = ClassRegistry::getObject('view');
$view->set($variable, ob_get_clean());
}
}
?>
// CONTROLLER:
// app/controllers/main_controller.php
<?php
class MainController extends AppController{
var $layout = 'app';
var $helpers = array('Cake');
function index(){
}
}
?>
// LAYOUT:
// app/views/layouts/app.ctp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>My App</title>
</head>
<body>
<div id="content">
<?=$content_for_layout?>
</div>
<div id="side">
<?=$side_for_layout?>
</div>
</div>
</body>
</html>
// VIEW:
// app/views/main/index.ctp
<? $cake->capture() ?>
This content is for side_for_layout.
<? $cake->content_for('side_for_layout') ?>
This content is for content_for_layout.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment