template class

By sean on Mar 13, 2010

a simple template class to separate design from code (mvc). similar to the ever popular smarty framework, just not nearly as big lol


<body>This [@WOULD] be [@EXAMPLE]</body>


$template = new Template('example.html');
$args = array( 'WOULD' => 'would', 'EXAMPLE' => 'an <i>example</i>' );
$template->set( $args );

anything passed to set() needs to be in array format. when instantiating Template, argument needs to be location of html. the above example, the result of example.php would be:
This would be an example

 *  @author Sean Wragg <seanwragg@gmail.com>
 *  @version 1.2 bRC3 template.class.php

class Template {
    protected $file; 
    public $values;

    // attempt to locate file upon instantiation
    function __construct( $file ) {
        if ( !file_exists( $file ) ) die('unable to locate file');
        $this->file = $file;

    // arg must be an array
    public function set( $values ) {
        foreach( $values as $key => $value ) {
            $this->values[$key] = $value;

    // render's html with keys replaced
    public function renderHTML() {
        $contents = file_get_contents( $this->file );
        foreach( $this->values as $key => $value ) {
            $contents = str_replace( '[@'. $key .']', $value, $contents ); 
        echo $contents;



Sign in to comment.
sean   -  Mar 15, 2010

@Korvin: it's only replacing keys that exist which are explicitly defined using set(). there was no need to add any further check.

@Hawkee: that's an excellent idea thanks :)

Hawkee   -  Mar 14, 2010

sean, exactly. For example:

Login Form

Korvin   -  Mar 14, 2010

i'd add a check to make sure that the key exists, and if not return [@KEY]

sean   -  Mar 14, 2010

considering all things server side would by dynamic, i assume you mean [en|dis]abling HTML code blocks?

Hawkee   -  Mar 13, 2010

Simple and to the point, but it could definitely use some additional functionality such as enabling and disabling code blocks.

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.