Search code examples
phptemplate-engine

Template engine {var} doesnt work


I have made a template system but the {var} doesnt output the worth. It just output {var}.

Here is my template class:

<?php
class Template {
    public $assignedValues = array();
    public $tpl;

    function __construct($_path = '')
    {
        if(!empty($_path))
        {
            if(file_exists($_path))
            {
                $this->tpl = file_get_contents($_path);
            }
            else
            {
                echo 'Error: No template found. (code 25)';
            }
        }
    }

    function assign($_searchString, $_replaceString)
    {
        if(!empty($_searchString))
        {
            $this->assignedValues[strtoupper($_searchString)] = $_replaceString;
        }
    }

    function show()
    {
        if(count($this->assignedValues) > 0)
        {
            foreach ($this->assignedValues as $key => $value)
            {
                $this->tpl = str_replace('{'.$key.'}', $value, $this->tpl);
            }
        }
        echo $this->tpl;
    }
}

?>

And here is what I execute on the index:

<?php
    require_once('inc/classes/class.template.php');
    define('PATH', 'tpl');

    //new object
    $template = new Template(PATH.'/test.tpl.html');

    //assign values
    $template->assign('title', 'Yupa');
    $template->assign('about', 'Hello!');

    //show the page
    $template->show();

?>

I really need some help, if you can help I'd would be very grateful.


Solution

  • Instead of line:

    $this->assignedValues[strtoupper($_searchString)] = $_replaceString;
    

    You should have:

    $this->assignedValues[$_searchString] = $_replaceString;
    

    and it will work.

    Of course I assume that inside your template file you have content:

    {title} {about}