Herzlich Willkommen, lieber Gast!
  Sie befinden sich hier:

  Forum » PHP » Templates

Forum | Hilfe | Team | Links | Impressum | > Suche < | Mitglieder | Registrieren | Einloggen
  Quicklinks: MSDN-Online || STL || clib Reference Grundlagen || Literatur || E-Books || Zubehör || > F.A.Q. < || Downloads   

Autor Thread - Seiten: [ 1 ] > 2 <
010
15.05.2005, 15:41 Uhr
Pablo
Supertux
(Operator)


Ich habe mir meine eigene Template Klasse geschrieben, weil die anderen die im Netz gibt, fand ich zu übertriebend. Ansonten siehe hier: www.dev-geeks.org/index.php?module=scripts&sub=4&action=show&id=8 aber ich habe schon paar Stellen geändert:

class.EasyTemplate.php

PHP 4:
<?php
/********************************************************
* The source code is the source code of a free software *
* and may be used under the term of the general public    *
* license (GPL) of the free software fundation.     *
*                            *
* Author: Pablo Yanez Trujillo              *
* Filename: scripts/class.Template.php            *
* Date:    28.05.04                    *
*********************************************************/


/*
    File description:
    Creates a class that parse templates
*/


if(!defined("INDEX"))
    die("Access denied");

    

define("FILE_NOT_FOUND", 1);
define("FILE_NO_ACCESS", 2);
define("WRONG_TEMPLATE", 3);
define("PARSE_ERROR", 4);
define("WRONG_ASSIGN", 5);
define("WRONG_ORDER", 6);


$err_db = array(
    FILE_NOT_FOUND     => "file not found",
    FILE_NO_ACCESS    => "access denied",
    WRONG_TEMPLATE    => "your templates array is wrong or you didn't pass an array",
    PARSE_ERROR    => "errors while parsing",
    WRONG_ASSIGN    => "you have used the assign method bad",
    WRONG_ORDER    => "you must use set_templates before using change_templates"
      );

/******************************************************
**
* Class EasyTemplate
*
* Synopsis: This class reads template file (.tpl) and
* parse them with the text you set on it. This is very
* useful, when you want to separate your php code from
* the layout of the website.
*
* You are able to create indepent scripts (login procedure,
* and so on) without thinking about the layout.
*
* @author              Pablo Yanez Trujillo
* @copyright       (C) Pablo Yanez Trujillo, 2004
* @version             0.0.2
********************************************************/


class EasyTemplate
{
    /**
     * Contains the whole body of the template
     * @var        mixed
     * @access    public
     */

    var $tpl_body = "";
    /**
     * Contains the directory where the templates
     * are saved
     * @var        mixed
     * @access    public
     */

    var $tpl_location = "";
    /**
      * Array with filelist
     * @var        mixed
     * @access    public
     */

    var $tpl_filelist = array();
    /**
     * Array with the variable to be parsed
     * @var        mixed
     * @access    public
     */

    var $tpl_parse_vars = array();
    /**
     * last error id. if 0 no error
     * @var        mixed
     * @access    public
     */

    var $tpl_err_number = 0;
    /**
     * last error message, if $this->tpl_parse_vars=0
     * then the string is empty
     * @var        mixed
     * @access    public
     */

    var $tpl_err_msg="";

    function check_for_errors()
    {
        global $err_db;
        if ($this->tpl_err_number) {
            $msg = "Error using QuickTemplate class<p>\n";
            $msg = "\"" . $this->tpl_err_msg . "\", ";
            $msg .= "exiting with error <b>" . $this->tpl_err_number;
            $msg .= "</b>: <i>" . $err_db[$this->tpl_err_number] ."</i>\n";
            die($msg);
        }
    }

    function clear_err_flags()
    {
        $this->tpl_err_number=0;
        $this->tpl_err_msg="";
    }

    /**
    *
    * Creates a new template. If  path is not passed
    * QuickTemplate uses the current directory.
    *
    * @return    mixed     Description
    * @access    public
    * @see        QuickTemplate
    */

    function EasyTemplate($path=".") {
        if ($path[strlen($path)-1]!="/") $path .= "/";
        $this->tpl_location=$path;
    }

    /**
    *
    * Pass an array with the alias and only the file name
    * of the template. Example
    * $tpl->set_templates(array('main' => 'main.tpl'));
    *
    * @access    public
    * @see        QuickTemplate
    */

    function set_templates($templates_array) {
        $this->clear_err_flags();
        if ($templates_array==array()) {
            $this->tpl_err_number=WRONG_TEMPLATE;
            $this->tpl_err_msg="You passed an empty array";
        } elseif (!is_array($templates_array)) {
            $this->tpl_err_number=WRONG_TEMPLATE;
            $this->tpl_err_msg="You have to use an array";
        } else {
            $this->tpl_filelist=$templates_array;
        }
        $this->check_for_errors();
    }

    /**
    *
    * The array you may pass have to have the same format as the one of the
    * set_templates function. You can change with this function the files of
    * your templates and even add new templates. Take care of the key names
    * because if you use key, that has been already used, the key will be
    * overwritten by the new value. You can use this function only when you used
    * set_templates at least one time.
    *
    * @return    nothing
    * @access    public
    * @see        set_templates
    */

    function change_templates($templates_array)  
    {
        $this->clear_err_flags();
        if ($templates_array==array()) {
                        $this->tpl_err_number=WRONG_TEMPLATE;
                        $this->tpl_err_msg="You passed an empty array";
        } elseif (!is_array($templates_array)) {
                        $this->tpl_err_number=WRONG_TEMPLATE;
                        $this->tpl_err_msg="You have to use an array";
        } elseif ($this->tpl_filelist==array())
        {
            $this->tpl_err_number=WRONG_ORDER;
                        $this->tpl_err_msg="Wrong order by calling the functions";
        } else {
            $this->tpl_filelist = array_merge($this->tpl_filelist, $templates_array);
        }
        
        $this->check_for_errors();
    }
    

    /**
    *
    * Set the $content of $varname of $alias template.
    * If $add=1, then you will add the new content to the old content.
    * When you parse the contents will be deleted
    *
    * @return    array     Description
    * @access    public
    * @see        set_templates
    */


    function assign($alias, $varname="", $content="", $add=1)
    {
        /* This function checks first whether $alias is an array.
           If so, then the new assign version is used, varname, content and add must
           be blank. */

           $this->clear_err_flags();

        if (is_array($alias)) {
            if($varname!="" or $content!="" or $add != 1) {
                $this->tpl_err_number=WRONG_ASSIGN;
                            $this->tpl_err_msg="All other arguments must be blank";
            } else {
                $this->__assign_a($alias);
            }
        } else /* old function */
        $this->__assign_t($alias, $varname, $content, $add);
        $this->check_for_errors();        
    }

    function __assign_a($arr)
    {    
        if ($arr==array()) {
            $this->tpl_err_number=WRONG_ASSIGN;
                        $this->tpl_err_msg="This is blank array";
            return;
        }

        foreach($arr as $array => $value)
        {
            $alias = $value['alias'];
            unset($value['alias']);
            $add = isset($value['add']) ? $value['add'] : 0;
            unset($value['add']);
            foreach($value as $key => $val)
            {
                $this->__assign_t($alias, $key, $val, $add);
            }
        }
        
    }

    
    function __assign_t($alias, $varname, $content, $add) {
        /*echo "<pre>\n";
        echo "\$this->tpl_parse_vars\n";
        print_r($this->tpl_parse_vars);
        echo "</pre>\n"; debug information only! */

        $this->clear_err_flags();
        if (!isset($this->tpl_parse_vars[$alias][$varname]))
            $this->tpl_parse_vars[$alias][$varname]="";
        
        if ($add) {
            $this->tpl_parse_vars[$alias][$varname] .= $content;
        } else {
            $this->tpl_parse_vars[$alias][$varname] = $content;
        }
    }
    
    /**
    *
    * returns the body that was parsed
    *
    * @return    mixed     Description
    * @access    public
    * @see        parse
    */

    function get_body() {
        $this->clear_err_flags();
        return $this->tpl_body;
    }

    /**
    *
    * If you want to get the content of a template file
    * you have to parse the template. $alias is the alias
    * name of a template. You have to call set_template and
    * assign before parse. Parse open the template file and then
    * search for variables and change their values. If the alias
    * wasn't assigned before, then parse won't be able to work.
    * You can get the parse text with the function get_body().
    * When the parse process is done, the temporal variable with
    * the parse temprals will be deleted. When you parse again,
    * you will loose the old content.
    *
    * @return    mixed     Description
    * @access    public
    * @see        assign,get_body
    */

    function parse($alias, $clear=1) {
        $this->clear_err_flags();
        /* check whether assign was made */
        if (!isset($this->tpl_parse_vars[$alias])) {
            /* template contains only text */
            $this->tpl_parse_vars=array_merge($this->tpl_parse_vars,array($alias => array()));
            /*$this->tpl_err_number=PARSE_ERROR;
            $this->tpl_err_msg = "Alias '$alias' was not set, yet";
            $this->check_for_errors();
            old style, don't use it! */

        }
        /* check whether set_templates was made */
        if(!isset($this->tpl_filelist[$alias])) {
            $this->tpl_err_number=PARSE_ERROR;
            $this->tpl_err_msg = "Alias '$alias' is not known";
            $this->check_for_errors();                        
        }
        /* check wheter file exists */
        $fn = $this->tpl_location . $this->tpl_filelist[$alias];
        if(!file_exists($fn)) {
            $this->tpl_err_number=FILE_NOT_FOUND;
            $this->tpl_err_msg = "Error while opening the file <b>$fn</b>";
            $this->check_for_errors();
        }
        $file = @fopen($fn, "r");
        if (!$file) {
            $this->tpl_err_number=FILE_NO_ACCESS;
            $this->tpl_err_msg = "File <b>$fn</b> cannot be opend";
            $this->check_for_errors();
        }
        $this->tpl_body="";
        while(!feof($file)) {
            $buffer = fgets($file);
            foreach($this->tpl_parse_vars[$alias] as $key => $value) {
                $buffer = ereg_replace("\{$key\}",  $value, $buffer);
            }
            $this->tpl_body.=$buffer;
        }
        @fclose($file);
        
        if ($clear) $this->tpl_parse_vars[$alias]=array();
    }

    /**
    *
    * This is the short Description for the Function
    *
    * This is the long description for the Class
    *
    * @return    mixed     Description
    * @access    public
    * @see        ??
    */


    function multiparse($array, $clear=1) {
        $this->clear_err_flags();
        if ($array == array())
        {
            $this->tpl_err_number=PARSE_ERROR;
            $this->tpl_err_msg = "This is an empty array";
            $this->check_for_errors();
        }

        /* Read the array */
        foreach($array as $parse => $value)
        {
            if(isset($value['last']) and $value['last']==1) {
                $this->parse($value[0], $clear);
            } else {

                $this->parse($value[0], $clear);
                $add = (isset($value[3]) and !$value[3]) ? 0 : 1;
                $this->assign($value[1], $value[2], $this->get_body(), $add);
            }
        }

        
        $this->check_for_errors();
    }
}

?>



Hier ein Beispiel, wie ich sie immer benutze:

header.inc.php

PHP 4:
<?php

if(!defined("INDEX"))
    die("Access denied");

if(!@include("class.EasyTemplate.php"))
    die("<b>Critical error</b><p>Cannot include Template engine");


/* each file must declare:
$website  ==> template file
$title ==> Titel

the website-template has alias `page` and
the main page alias `main_page`

*/


if(!isset($website))
    die("<b>Critical error</b><p>Cannot read template file");

if(!isset($title))
    die("<b>Critical error</b><p>Cannot read the title of the file");


$template = new EasyTemplate("templates");

$template->set_templates(array('main_page' => 'page.html',
                               'page' => $website));


$template->assign('main_page', 'TITLE', htmlentities($title));
?>



footer.inc.php

PHP 4:
<?php

if(!defined("INDEX"))
        die("Access denied");

$template->multiparse(array(array('page', 'main_page', 'MAIN'),
                                  array('last' => 1, 'main_page')));

echo $template->get_body();

?>



index.php

PHP 4:
<?php

define("INDEX", "1");

$website = "index.html";
$title = "INDEX";

include("header.inc.php");

/* zum beispiel hier braucht man nichts */

include("footer.inc.php");

?>



media.php

PHP 4:
<?php

define("INDEX", "1");

$website = "media.html";
$title = "MEDIA";

include("header.inc.php");

/* hier könnte man irgendetwas tun, z.b. aus 3 Namen einen zufällig wählen */

$namen = array('Marc', 'Florian', 'Pablo');

$name = $namen[rand()%3];

$template->assign('page', 'USER', htmlentities($name));

/*
oder auch so, ganz nützlich, wenn man mehrere alias auf einmal setzen will, oder
mehrere Variablen eines alias setzen will

$template->assign(array(array('alias' => 'page',
                  'USER' => htmlentities($name),
                  'ANDERE VARIABLE 1' => ???,
                  'ANDERE VARIABLE 2' => ???,
                  'USW...' => ???)));

                  */


include("footer.inc.php");

?>



audio.php

PHP 4:
<?php

define("INDEX", "1");

$website = "audio.html";
$title = "AUDIO";

include("header.inc.php");

/* neue templates hinzufügen */
$template->change_templates(array('table' => 'tabelle.html'));

$template->assign(array(array('alias' => 'page',
                  'USER' => 'Finrod Felagund',
                  'SOHNVON' => 'Finarfins Sohn'),

            array('alias' => 'table',
                'VATER' => 'Finarfin',
                'KIND1' => 'Finrod Felagund',
                'KIND2' => 'Orodreth',
                'KIND3' => 'Angrod',
                'KIND4' => 'Aegnor',
                'KIND5' => 'Galadriel')));

/* Template `table` in Variable page->{TABELLE} einbinden */

$template->multiparse(array(array('table', 'page', 'TABELLE')));

include("footer.inc.php");

?>



templates/page.html

Template XHTML:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de">
<head>
<title>Sample Page - [{TITLE}]</title>
<meta name="author" content="Pablo Yanez Trujillo" />
<meta name="Audience" content="Alle" />
<meta name="Expires" content="0" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="pragma" content="no-cache" />
<meta name="Robots" content="INDEX,FOLLOW" />
<meta name="Revisit-After" content="5 days" />
</head>
<body>
<p>
{MAIN}
</p>
    <table width="100%" border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td class="copyright" align="right" style="border:1px solid black; margin:0px;padding:5px;">
        <center><span style="font-size:65%; color: #6c6d6e">Sample Page - Version 1.0.0<br />
    <abbr title="Fun-Soft Administration Portal - Version 1.0.0">Copyright &copy; by Pablo Y&aacute;nez Trujillo, Apr. 2005. All rights reserved</abbr></span></center></td>
    </tr>
    </table>
</body>
</html>



templates/index.html

Template XHTML:

Hallo! Das ist eine Testseite.<br /><br />
Nun, hie ein Paar Links:<br />
<a href="media.php">media.php</a><br />
<a href="audio.php">audio.php</a>



templates/media.html

Template XHTML:

Hallo <b>{USER}</b><br /><br />
Du bist in media.php! <a href="index.php">[Zur&uuml;ck]</a>



templates/audio.html

Template XHTML:

Hallo <b>{USER}, {SOHNVON}</b><br /><br />
Du bist in audio.php! Und das Beste ist, dass der XHTML Code vom PHP Code getrennt ist, supi! <a href="index.php">[Zur&uuml;ck]</a><br />
Hier eine Tabelle:</p>
{TABELLE}
<p>Cool, oder?



templates/tabelle.html

Template XHTML:

<table border="1" align="center">
<tr>
  <th colspan="5">Die Kinder von {VATER}</th>
</tr>
<tr>
  <td>{KIND1}</td>
  <td>{KIND2}</td>
  <td>{KIND3}</td>
  <td>{KIND4}</td>
  <td>{KIND5}</td>
</tr>
</table>



Ein funktionierendes Beispiel @ http://fun-soft.ra-doersch.de/admin/test/
--
A! Elbereth Gilthoniel!
silivren penna míriel
o menel aglar elenath,
Gilthoniel, A! Elbereth!

Dieser Post wurde am 15.05.2005 um 15:56 Uhr von Pablo editiert.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
011
16.06.2006, 22:23 Uhr
FlAsH
keine Ahnung


Hi!
Ich habe bis heute die Template variante von Flosoft benutzt. Sie ist klein und funktioniert ohne probleme.

Doch jetzt sollte ich ein Template in einem Template aufrufen.

Also eigentlich wollte ich das so anwenden:

PHP 4:
$header = new TEMPLATE("templates/header.htm");
$layout = new TEMPLATE("templates/layout.htm");
eval($layout->get());



und in der HTML Datei sollte ich die header.htm dann so aufrufen können:

Code:
{$header}



Doch nun wird ja nur "Objekt" angezeigt.

Ich hoffe es kann mir jemand von euch helfen.
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
012
17.06.2006, 13:48 Uhr
FloSoft
Medialer Over-Flow
(Administrator)


klar, da $header ein objekt ist. benutz z.b so:


PHP 4:
$header = new TEMPLATE("templates/header.htm");
$layout = new TEMPLATE("templates/layout.htm");
$myheaderstr = $header->get();
eval($layout->get());



und dann im template


Code:
{$myheaderstr}


--
class God : public ChuckNorris { };
 
Profil || Private Message || Suche Download || Zitatantwort || Editieren || Löschen || IP
Seiten: [ 1 ] > 2 <     [ PHP ]  


ThWBoard 2.73 FloSoft-Edition
© by Paul Baecher & Felix Gonschorek (www.thwboard.de)

Anpassungen des Forums
© by Flo-Soft (www.flo-soft.de)

Sie sind Besucher: