Einfache Template Engine

Fragen zu allen Themen rund ums Programmieren außerhalb von phpBB können hier gestellt werden - auch zu anderen Programmiersprachen oder Software wie Webservern und Editoren.
Antworten
Gast210225

Einfache Template Engine

Beitrag von Gast210225 »

Hallo,
für ein kleines Projekt brauche ich eine einfache Template Engine, habe aber nichts gefunden. Also habe ich mich mal selber dran gemacht ;) soweit bin ich schon:

Code: Alles auswählen

/**
 * The template engine
 */
class template
{
	var $path;
	var $filename;
	var $uncopiled_code;
	var $copiled_code;
	var $vars = array();

	function template($path)
	{
		if ( is_dir($path) && !empty($path) )
		{
			$this->path = $path;
			return true;
		}
		else
		{
			die('<strong>Error: <strong> $template !<br />wrong path!');
			return false;
		}
	}

	function set_filename($filename)
	{
		if ( !empty($filename) )
		{
			$this->filename = $this->path . $filename;

			if ( !is_readable($this->filename) )
			{
				die('<strong>Error: <strong> $template->set_filename !<br />File isn\'t readable!');
				return false;
			}

			return true;
		}
		else
		{
			die('<strong>Error: <strong> $template->set_filename !<br />Filename is empty!');
			return false;
		}
	}

	function set_vars($vars)
	{
		if ( is_array($vars) && !empty($vars) )
		{
			$this->vars = array();

			//
			// From www.php.net ;)
			//
			reset ($vars);
			while ( list($key, $val) = each($vars) )
			{
				$this->vars[$key] = $val;
			}

			return true;
		}
		else
		{
			die('<strong>Error: <strong> $template->set_vars !<br />$vars is no array or is empty!');
			return false;
		}
	}

	function parse()
	{
		$this->uncopiled_code = file_get_contents($this->filename);

		reset ($this->vars);
		while ( list($key, $val) = each($this->vars) )
		{
			$this->copiled_code = str_replace('{' . $key . '}', '<?php echo \'' . $val . '\'; ?>', $this->uncopiled_code);
		}

		eval( '?>' . $this->copiled_code . '<?php' );
	}

}
(ich hoffe der Code ist nicht zu lang, aber ich kann mich gerade nicht auf per FTP einloggen....)

In der Datei, die die Template Engine nutzt steht folgendes:

Code: Alles auswählen

$path = './';
require($path . 'template.php');

$template_path = $path . 'styles/' . $config['style'] . '/';

$template = new template($template_path);

	$template->set_filename('header.html');
	$template->set_vars(array(
		'PAGE_TITLE' => 'Hallo ;)',
		'SITE_NAME' => 'Seiten Titel',
		'SITE_DESCRIPTION' => 'Beschreibung'
	));
	$template->parse();
und in der header.html steht folgendes:

Code: Alles auswählen

{PAGE_TITLE}<br />
{SITE_NAME}<br />
{SITE_DESCRIPTION}<br /><br />
Eigentlich gehen alle Funktionen, nur $template>parse(); geht nicht...

wisst ihr, was ich falsch mache, bzw. was ich verbessern könnte?


Johannes
Jack9027
Mitglied
Beiträge: 344
Registriert: 05.01.2004 18:46

Beitrag von Jack9027 »

hi hab grad leider keine zeit mit des genauer anzuschaun, aber ich hab mir vor langer zeit auch mal ne kleine template engine geschrieben ;)

Code: Alles auswählen

<?php
    class template
    {  
        var $str;
        var $vars             = array();
        var $block_vars = array();

        function set_filename($file)
        {
            $filename = $_SERVER["DOCUMENT_ROOT"].$GLOBALS["base_folder"]."/templates/".$file;
            $this->str = implode("", file($filename));                    
        }
    
        function assign_var($index, $wert)
        {
            $this->vars[$index] = $wert;  
        }
        
        function assign_vars($vars)
        {
            foreach($vars as $index => $wert) {
                $this->vars[$index] = $wert;
            }          
        }
        
        function assign_block_vars($blockname, $vars)
        {
             $this->block_vars[$blockname][] = $vars;                 
        }
           
        function parse()
        {
            //begin parse $this->var/s         
            foreach ($this->vars as $search => $replace) {
            $search = "{".$search."}";            
            $this->str = str_replace($search, $replace, $this->str);
            }
            //end parse $this->var/s
            
            //begin parse $this->block_vars
            foreach ($this->block_vars as $blockname => $vars_array) {
                $final_str = "";
                preg_match("/<!-- BEGIN ".$blockname." -->(.*)<!-- END ".$blockname." -->/s", $this->str, $search_array);
                foreach ($this->block_vars[$blockname] as $index => $wert) {
                    $i=0;
                        foreach ($this->block_vars[$blockname][$index] as $index => $wert) {
                            if ($i == 0) {
                                $final_str .= str_replace("{".$blockname.".".$index."}", $wert, $search_array[1]);
                                $i++;                                                                
                            } else {                                
                                $final_str = str_replace("{".$blockname.".".$index."}", $wert, $final_str);                                
                            }
                        }
                }       
                                        
                $this->str = preg_replace("/<!-- BEGIN ".$blockname." -->(.*)<!-- END ".$blockname." -->/s", $final_str, $this->str);                
            }
            //endparse $this->block_vars
                                $this->str = preg_replace("/<!-- BEGIN (.*) -->(.*)<!-- END (.*) -->/s", "", $this->str);
                                $this->str = preg_replace("/\{(.*)\}/", "", $this->str);
            return $this->str;
        }
    } 
?>
musst halt paar kleinere sachen ängern wie z.b des $GLOBALS["base_folder"] ( was hab ich mir damals dabei gedacht ;))

grüsse
123teddy321
Mitglied
Beiträge: 290
Registriert: 29.07.2005 17:27
Kontaktdaten:

Beitrag von 123teddy321 »

ich kann dir eines geben, ist selber gemacht!
melde dich mal per ICQ oder PN!
Gast210225

Beitrag von Gast210225 »

Warum postest du es hier nicht?
Gast210225

Beitrag von Gast210225 »

Hallo,
ich hab an der Funktion parse() weitergebastelt:

Code: Alles auswählen

	function parse()
	{
		$this->uncopiled_code = file_get_contents($this->filename);

		reset ($this->vars);
		while ( list($key, $val) = each($this->vars) )
		{
			$this->uncopiled_code = str_replace('{' . $key . '}', '<?php echo \'' . $val . '\'; ?>', $this->uncopiled_code);
		}

		$this->uncopiled_code = str_replace('$', '\$', $this->uncopiled_code);

		eval (' ?> ');
		eval ($this->uncopiled_code);
		eval (' <?php ');
	}
Nur ich bekomme immer einen Parse Error:

Code: Alles auswählen

Parse error: syntax error, unexpected '<' in /www/htdocs/verzeichniss/template.php(105) : eval()'d code on line 1

Parse error: syntax error, unexpected '<' in /www/htdocs/verzeichniss/template.php(106) : eval()'d code on line 1
Wenn ich das eval durch echo() ersetze kommt folgendes raus:

Code: Alles auswählen

<?php echo 'Hallo ;)'; ?><br />
<?php echo 'Seiten Titel'; ?><br />
<?php echo 'Beschreibung'; ?><br /><br />

des passt ja eigentlich...

Wisst ihr, wo mein Fehler ist?
PhilippK
Vorstand
Vorstand
Beiträge: 14662
Registriert: 13.08.2002 14:10
Wohnort: Stuttgart
Kontaktdaten:

Beitrag von PhilippK »

Wieso nicht einfach Smarty verwenden?

Gruß, Philipp
Kein Support per PN!
Der Sozialstaat ist [...] eine zivilisatorische Errungenschaft, auf die wir stolz sein können. Aber der Sozialstaat heutiger Prägung hat sich übernommen. Das ist bitter, aber wahr. (Horst Köhler)
Meine Mods
Gast210225

Beitrag von Gast210225 »

Weil ich es vllt. auch mal veröffentlichen will ;)
PhilippK
Vorstand
Vorstand
Beiträge: 14662
Registriert: 13.08.2002 14:10
Wohnort: Stuttgart
Kontaktdaten:

Beitrag von PhilippK »

JG hat geschrieben:Weil ich es vllt. auch mal veröffentlichen will ;)
Smarty ist frei verfügbar - wo ist das Problem?

Gruß, Philipp
Kein Support per PN!
Der Sozialstaat ist [...] eine zivilisatorische Errungenschaft, auf die wir stolz sein können. Aber der Sozialstaat heutiger Prägung hat sich übernommen. Das ist bitter, aber wahr. (Horst Köhler)
Meine Mods
Gast210225

Beitrag von Gast210225 »

Ja, schon, aber das CMS sollte klein und schnell bleiben, also ohne viele Extras,... und da ist Smarty überdimensioniert ;)
Gast210225

Beitrag von Gast210225 »

Hallo,
nun gehts ;)
Ich weiß zwar nicht warum, aber es geht ;)
Hier die parse():

Code: Alles auswählen

	function parse()
	{
		$this->uncopiled_code = file_get_contents($this->filename);

		reset ($this->vars);
		while ( list($key, $val) = each($this->vars) )
		{
			$this->uncopiled_code = str_replace('{' . $key . '}', '<?php echo "' . $val . '"; ?>', $this->uncopiled_code);
		}

		$this->uncopiled_code = str_replace('$', '\$', $this->uncopiled_code);

		eval ('?>' . $this->uncopiled_code);
	}
Edit:
ich hab parse() nun noch einwenig verändert:

Code: Alles auswählen

	function parse()
	{
		$this->code = file_get_contents($this->filename);

		$this->code = str_replace('<?php', '<?php', $this->code);
		$this->code = str_replace('<? ', '<? ', $this->code);
		$this->code = str_replace('?>', '?>', $this->code);

		reset ($this->vars);
		while ( list($key, $val) = each($this->vars) )
		{
			$this->code = str_replace('{' . $key . '}', '<?php echo "' . $val . '"; ?>', $this->code);
		}

		$this->code = str_replace('$', '\$', $this->code);

		//
		// Fix for German "Umlaute"
		//
		$this->code = str_replace('ä', '&auml;', $this->code);
		$this->code = str_replace('ö', '&ouml;', $this->code);
		$this->code = str_replace('ü', '&uuml;', $this->code);
		$this->code = str_replace('Ä', '&Auml;', $this->code);
		$this->code = str_replace('Ö', '&Ouml;', $this->code);
		$this->code = str_replace('Ü', '&Uuml;', $this->code);

		//
		// Fix for the Euro character
		//
		$this->code = str_replace('€', '&euro;', $this->code);

		//
		// Parse
		//
		eval ('?>' . $this->code);
	}


aber nun kommt ein parse Error, wenn ich in der Datei "<?xml version="1.0" encoding="utf-8"?>" stehen hab, kommt ein parse error... wie kann ich das ändern?


Johannes
Antworten

Zurück zu „Coding & Technik“