ANTICHAT.XYZ    VIDEO.ANTICHAT.XYZ    НОВЫЕ СООБЩЕНИЯ    ФОРУМ  
Баннер 1   Баннер 2
Antichat снова доступен.
Форум Antichat (Античат) возвращается и снова открыт для пользователей. Здесь обсуждаются безопасность, программирование, технологии и многое другое. Сообщество снова собирается вместе.
Новый адрес: forum.antichat.xyz
Вернуться   Форум АНТИЧАТ > Программирование > PHP, PERL, MySQL, JavaScript
   
 
 
Опции темы Поиск в этой теме Опции просмотра

Шаблонизатор от DLE
  #1  
Старый 11.03.2010, 10:11
Аватар для Fox_NICK
Fox_NICK
Новичок
Регистрация: 10.01.2007
Сообщений: 21
Провел на форуме:
175230

Репутация: 15
По умолчанию Шаблонизатор от DLE

Шаблонизатор от DLE
Вот решил выложить на мой взгляд очень полезную штуку) шаблонизатор скрученный с ДЛЕ, но немного изменен, думаю многим должно помочь в написании своей CMS ну и т.д ))
Что можно сказать о его возможностях!?
Возможность добавлять php код в tpl, вывод переменных такого типа : {.....}
Ну а дальше я думаю разберитесь

Код index.php =)

PHP код:
<?

include("templates.class.php"); //подключение class

$tpl    = new Template//инициируем класс
$tpl->dir 'template/'//задаём местоположение папки с шаблонами
$tpl->load_template('main.tpl'); //загружаем каркас
$tpl->set('{sub_templ}'$tpl->sub_load_template('sub.tpl')); //подключаем код блока

//подставляем значения переменных
$tpl->set('{var1}''блок2');
$tpl->set('{var2}''блок3');

$tpl->compile('main'); //собираем шаблон
eval (' ?' '>' $tpl->result['main'] . '<' '?php '); //выводим результат работы, с возможностью вставки пхп кода в tpl
$tpl->global_clear(); //очищаем все переменные для возможно следующего шаблона

?>

Код templates.class.php

PHP код:
<?php

class Template {

    public  
$dir '.';
    public  
$template null;
    public  
$copy_template null;
    public  
$data = array();
    public  
$block_data = array();
    public  
$result = array('info' => '''content' => '');
    public  
$template_parse_time 0;

//задаём параметры основных переменных подгрузки шаблона

    
public function set($name $var) {
        if (
is_array($var) && count($var)) {
            foreach (
$var as $key => $key_var) {
                
$this->set($key $key_var);
            } } else 
$this->data[$name] = $var;
    }

//обозначаем блоки

    
public function set_block($name $var) {
        if (
is_array($var) && count($var)) {
            foreach (
$var as $key => $key_var) {
                
$this->set_block($key $key_var);
            } } else 
$this->block_data[$name] = $var;
    }

//производим загрузку каркасного шаблона

    
public function load_template($tpl_name) {
    
$time_before $this->get_real_time();
        if (
$tpl_name == '' || !file_exists($this->dir DIRECTORY_SEPARATOR $tpl_name)) { die ("Невозможно загрузить шаблон: "$tpl_name); return false;}
        
$this->template file_get_contents($this->dir DIRECTORY_SEPARATOR $tpl_name);
        if ( 
stristr$this->template"{include file=" ) ) {
            
$this->template preg_replace"#\\{include file=['\"](.+?)['\"]\\}#ies","\$this->sub_load_template('\\1')"$this->template);
        }
        
$this->copy_template $this->template;
    
$this->template_parse_time += $this->get_real_time() - $time_before;
    return 
true;
    }

// этой функцией загружаем "подшаблоны"

    
public function sub_load_template($tpl_name) {
        if (
$tpl_name == '' || !file_exists($this->dir DIRECTORY_SEPARATOR $tpl_name)) { die ("Невозможно загрузить шаблон: "$tpl_name); return false;}
        
$template file_get_contents($this->dir DIRECTORY_SEPARATOR $tpl_name);
        return 
$template;
    }

// очистка переменных шаблона
    
public function _clear() {
    
$this->data = array();
    
$this->block_data = array();
    
$this->copy_template $this->template;
    }

    public function 
clear() {
    
$this->data = array();
    
$this->block_data = array();
    
$this->copy_template null;
    
$this->template null;
    }
//полная очистка включая результаты сборки шаблона
    
public function global_clear() {
    
$this->data = array();
    
$this->block_data = array();
    
$this->result = array();
    
$this->copy_template null;
    
$this->template null;
    }
//сборка шаблона в единое целое
    
public function compile($tpl) {
    
$time_before $this->get_real_time();
    foreach (
$this->data as $key_find => $key_replace) {
                
$find[] = $key_find;
                
$replace[] = $key_replace;
            }
    
$result str_replace($find$replace$this->copy_template);
    if (
count($this->block_data)) {
        foreach (
$this->block_data as $key_find => $key_replace) {
                
$find_preg[] = $key_find;
                
$replace_preg[] = $key_replace;
                }
    
$result preg_replace($find_preg$replace_preg$result);
    }
    if (isset(
$this->result[$tpl])) $this->result[$tpl] .= $result; else $this->result[$tpl] = $result;
    
$this->_clear();
    
$this->template_parse_time += $this->get_real_time() - $time_before;
    }
//счётчик времени выполнения запросов сборки
    
public function get_real_time()
    {
        list(
$seconds$microSeconds) = explode(' 'microtime());
        return ((float)
$seconds + (float)$microSeconds);
    }
}

?>

Ну вот и все) желаю удачи!

Последний раз редактировалось Fox_NICK; 13.03.2010 в 12:57..
 
Ответить с цитированием
 



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Продам лицензию на DLE, DLE Forum, DLE Grabber Zake73 Разное - Покупка, продажа, обмен 7 08.03.2010 15:52
Cоздание своей nulled CMS на примере DLE SchmeL Статьи 17 19.04.2009 14:21
DLE База / DLE Site Checker KingSise Разное - Покупка, продажа, обмен 1 31.12.2008 23:09



Здесь присутствуют: 1 (пользователей: 0 , гостей: 1)
 


Быстрый переход




ANTICHAT.XYZ