Organisation of includes

Introduction

A solution

mechanism

block

file: plugins/block.head.php

<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */

/**
 * Smarty {head} block plugin
 *
 * Filename: block_head.php<br>
 * Type:     block<br>
 * Name:     head<br>
 * Date:     April 28, 2006<br>
 * Purpose:  move all content in headblocks to the header of the html document
 *
 * Examples:<br>
 * <pre>
 * {head}
 *    <style type="text/css">
 *       h1{font-family:fantasy;}
 *    </style>
 * {/head}
 * </pre>
 * @author Mathias Baert <mathias@motionmill.com>
 * @version  0.1
 * @param array
 * @param string
 * @param Smarty
 * @param boolean
 * @return string
 */
function smarty_block_head($params, $content, &$smarty, &$repeat){
    if ( empty($content) ) {
        return;
    }
    return '@@@SMARTY:HEAD:BEGIN@@@'.trim($content).'@@@SMARTY:HEAD:END@@@';
}
?>

filter

file: outputfilter.move_to_head.php

<?php
/**
* outputfilter adds content of {head}-blocks to document<head>
* @param string
* @param Smarty
* @return string
*/
function smarty_outputfilter_move_to_head($tpl_output, &$smarty)
{
    $matches = array();
    preg_match_all('!@@@SMARTY:HEAD:BEGIN@@@(.*?)@@@SMARTY:HEAD:END@@@!is', $tpl_output, $matches);
    $tpl_output = preg_replace("!@@@SMARTY:HEAD:BEGIN@@@(.*?)@@@SMARTY:HEAD:END@@@!is", '', $tpl_output); 
    return str_replace('</head>', implode("\n", array_unique($matches[1]))."\n".'</head>', $tpl_output);
}
?>

Usage

$template = new Smarty();
// do stuff
$template->load_filter('output', 'move_to_head');
// do stuff
$template->display($filename);

TODO

 {head}
     <link rel="stylesheet" type="text/css" href="global.css" />
 {/head}
 {head}
        <link rel="stylesheet" type="text/css" href="global.css" />
 {/head}
 {head}
     <link rel="stylesheet" type="text/css" href="global.css" />
     <style type="text/css">
         ...
     </style>
 {/head}

will become

 <head>
     ...OLD HEAD...
     <link rel="stylesheet" type="text/css" href="global.css" />
     <link rel="stylesheet" type="text/css" href="global.css" />
     <style type="text/css">
         ...
     </style>
 </head>