Prosta klasa szablonów w PHP

Stworzyłem tą klasę jakiś czas temu, na własny użytek, i stwierdz­iłem, że doskonale zastępuje inne tego typu klasy. Skład­nia szablonów wygląda tak jak w word­pressie, czyli zwykły kod php, osad­zony w szablonach.

Jeśli masz pomysł jak ulep­szyć tą klasę, dodać nową funkcjon­al­ność, lub po prostu znalazłeś błąd, proszę o kon­takt ;) Å»yczę miłego używania!

Wer­sja do ściągnięcia/skopiowania.

< ?php
/* * * * * * * * * * * *

Licenced for use under the LGPL. See http://www.gnu.org/licenses/lgpl-3.0.txt.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This licence is there: http://www.gnu.org/licenses/lgpl-3.0.txt.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS /FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

* * * * * * * * * * * * */

/*
 * Filename: templates.class.php
 * Author: Dawid "nazgul" Dziurdzia
 * Licence: LGPL v3.0
 */

class Template
{
    protected $_path;
    protected $_vars = array();
    protected $_result;

    public function Template($path)
    {
        $this->_path = $path;
    } //end constructor

    public function set($name, $value)
    {
        if(!isset($this->_vars[$name]))
        {
            $this->vars[$name] = $value;
        }
    } //end set()

    public function renderTemplate()
    {
        ob_start(); //włączamy buforowanie

        $filename = $this->_path;
        $keys = array_keys($this->vars);

        for ($i=0; $ivars); $i++) //pętla po elementach $vars (przypisujemy zmiennym ($key) wartości z tablicy)
        {
            $key = $keys[$i];
            global ${$key};
            ${$key} = $this->vars[$key];
        }		

        // require_once('/inc/template_helper.php');  //dołączamy plik z funkcajmi pomocniczymi
        require_once($filename); //przetwarzamy plik szablonu

        $output = ob_get_contents(); //pobieramy zawartość bufora do zmiennej

        ob_end_clean(); //kończymy buforować

        $this->_result = $output();
    } //end renderTemplate()

    public function printTemplate()
    {
         echo $this->_result; //wypisujemy rezultat na ekran
    } //end printTemplate()

} //end Template

?>

No related posts.

Pow­iązane wpisy wygen­erowane przez wty­czkę Yet Another Related Posts.

Ten wpis został opublikowany w kategorii Internet, Programowanie. Dodaj zakładkę do bezpośredniego odnośnika.

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany.

Możesz użyć następujących tagów oraz atrybutów HTML-a: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>