Skip to content

Instantly share code, notes, and snippets.

@nicooprat
Last active February 25, 2018 18:45
Show Gist options
  • Save nicooprat/2fbdfbf08344a820097cc62166772136 to your computer and use it in GitHub Desktop.
Save nicooprat/2fbdfbf08344a820097cc62166772136 to your computer and use it in GitHub Desktop.
Simple PHP block yielding system
<?php
function block($slug, $params = array()) {
global $_SLUG_;
global $_PARAMS_;
$_SLUG_ = $slug;
$_PARAMS_ = $params;
ob_start();
}
function endblock() {
global $_SLUG_;
global $_PARAMS_;
$yield = ob_get_clean();
if(!isset($yield) || empty($yield)) $yield = '';
foreach($_PARAMS_ as $key => $value) {
$$key = $value;
}
$path = dirname(__FILE__) . '/' . $_SLUG_;
require($path);
unset($GLOBALS['_SLUG_']);
unset($GLOBALS['_PARAMS_']);
}
?>
<div class="<?php echo $class ?>">
<?php echo $yield; ?>
</div>
<?php block('templates/child.php', array('class' => 'first')); ?>
<p>Child 1</p>
<?php endblock(); ?>
<?php block('templates/child.php', array('class' => 'second')); ?>
<p>Child 2</p>
<?php endblock(); ?>
<div class="first">
<p>Child 1</p>
</div>
<div class="second">
<p>Child 2</p>
</div>
@nicooprat
Copy link
Author

Be sure your php.ini has output_buffering = On.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment