Saturday, July 30, 2011

Slot Helper

Introduction
Symfony Slot like function.
http://www.symfony-project.org/book/1_0/07-Inside-the-View-Layer#chapter_07_sub_slots

Require library
http://codeigniter.com/wiki/layout_library/

Source
helpers/slot_helper.php

<?php
function slot($name){
Slot::setName($name);
ob_start();
}
function end_slot(){
$name=Slot::getName();
Slot::set($name,ob_get_contents());
ob_end_clean();
}
function get_slot($name,$default=''){
return ( Slot::get($name)==false )?$default:Slot::get($name);
}
class Slot{
static $name='';
static $content=array();
static function setName($in){
self::$name=$in;
}
static function getName(){
return self::$name;
}
static function set($key,$val){
self::$content[$key].=$val;
}
static function get($key){
if( !isset(self::$content[$key]) ){
return false;
}
return self::$content[$key];
}
}

?>


Usage

template.php

<html >
<head>
<title><?php echo get_slot('html_title',''); ?></title>
<?php echo get_slot('html_head',''); ?>
</head>
<body>
<?php echo get_slot('html_body',''); ?>
</body>
</html>


view_file.php

<?php slot('html_title'); ?>
I am page title.
<?php end_slot(); ?>

<?php slot('html_head'); ?>
<!-- Hi! This content will be show inside head tag. -->
<script type=\"text/javascript" src="../nav/nav.js"></script>
<?php end_slot(); ?>

<?php slot('html_body'); ?>
Hi! This content will be show inside body tag.
<?php end_slot(); ?>


Output

<html >
<head>
<title>
I am page title.
</title>
<!-- Hi! This content will be show inside head tag. -->
<script type=\"text/javascript" src="../nav/nav.js"></script>
</head>
<body>
Hi! This content will be show inside body tag.
</body>
</html>

No comments:

Post a Comment