Форум АНТИЧАТ

Форум АНТИЧАТ (https://forum.antichat.xyz/index.php)
-   PHP, PERL, MySQL, JavaScript (https://forum.antichat.xyz/forumdisplay.php?f=37)
-   -   light-engine (https://forum.antichat.xyz/showthread.php?t=184617)

AtomoS 07.03.2010 02:58

light-engine
 
Всем привет. неськолько месяцев назад начал разрабатывать новый бесплатный продукт: light_engine - это простая и лёгкая веб-обвязка для мморпг игры lineage2.

С тех времён я достиг многово, но одно мне не удалось сделать до сих пор - шаблонизатор.

Собственно я ищу чеговека кот.поможет мне его сделать для моей вебки.
Исходники и sql для БД предоставлю в icq.

m0Hze 07.03.2010 03:11

http://bit.ly/bshHSo
To read.

AtomoS 07.03.2010 06:22

одно to read, но другое to write..
я просто не могу взять любой шаблонизатор и прикрутить его себе.
я просто не пойму как это сделть в моём случае..

AtomoS 09.03.2010 08:03

need help.

LStr1ke 09.03.2010 10:06

Тема шаблонизации обсуждалась много раз. Юзай поиск.
Бесплатно врядли ты найдешь хорошего помошника

m0Hze 09.03.2010 12:55

Тут знаешь что самое главное,это то, что не нужно усердствовать в писании_велосипедов.
Много раз убеждался на собственном опыте,что если есть готовые варианты,лучше юзать их(в плане,хорошие варианты).Если тебе нужен простой шаблонизатор,с его обычным функционалом,то лучше использую готовые решения,проверенные временем и пользователями.Советую Smarty,Quick.
Но вот если тебе нужно индивидуальное решение,как извращенство с загрузкой шаблонов с соседенего сервера по ftp, их дальнейшей обработкой сначала десктопным приложением,а потом уже выводом(как пример),то тут уже придется писать свой код.

AtomoS 09.03.2010 15:57

кто желает попробовать => _http://dump.ru/file/4046646
я просто не пойму как мне всё это организовать.

Nelzone 09.03.2010 23:03

в index.php

PHP код:

<?php
require_once 'templates/templates.class.php';
$tpl = new template();

    
$tpl->load_template('header.tpl');
    
$tpl->set('{nameurl}'$nameurl);
    
$tpl->set('{deslurl}'$deslurl);
    
$tpl->compile('header');
    echo 
$tpl->result['header'];
    
$tpl->global_clear();
?>

шаблонизатор templates.class.php

PHP код:

<?php

class template {
    
    var 
$dir '.';
    var 
$template null;
    var 
$copy_template null;
    var 
$data = array();
    var 
$block_data = array();

    
/* дада это */
    
var $result = array('temp' => '',
                        
'vote' => '',
                        
'speedbar' => '',
                        
'content' => ''
                        
);

    var 
$template_parse_time 0;
    
    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;
    }

    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;
    }    
    
    function 
load_template($tpl_name) {
    
$time_before $this->get_real_time();

        if (
$tpl_name == '' || !file_exists($this->dir "/templates/" $tpl_name)) { die ("Невозможно загрузить шаблон: "$tpl_name); return false;}
        
$this->template file_get_contents($this->dir "/templates/" $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;
    }

    function 
sub_load_template($tpl_name) {

        
$tpl_name totranslit($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;
    }

    function 
_clear() {

    
$this->data = array();
    
$this->block_data = array();
    
$this->copy_template $this->template;

    }

    function 
clear() {

    
$this->data = array();
    
$this->block_data = array();
    
$this->copy_template null;
    
$this->template null;

    }

    function 
global_clear() {

    
$this->data = array();
    
$this->block_data = array();
    
$this->result = array();
    
$this->copy_template null;
    
$this->template null;

    }
    
    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;
    }

    function 
get_real_time()
    {
        list(
$seconds$microSeconds) = explode(' 'microtime());
        return ((float)
$seconds + (float)$microSeconds);
    }
}
?>

дальше сам крути под себя...


AtomoS 10.03.2010 09:01

видел такое. пытался. но нифига не молучилось у меня..

Nelzone 10.03.2010 10:28

значит руки не отуда растут бросай :(

BlackSun 10.03.2010 10:53

PHP код:

<?php
    
class Template {
        
/**
         * Переменные шаблона
         *
         * @var array
         */
        
protected $vars;
        
/**
         * Файл шаблона
         *
         * @var string
         */
        
private $template;
        public 
$tblocks;
        
        public function 
__construct() {
            
$this->vars = array();
            
$this->template '';
            
$this->tblocks = array();
        }
        
        
/**
         * Объявить переменную шаблона
         *
         * @param string $var
         * @param string $value
         */
        
public function set($var$value '') {
            
$this->vars[$var] = $value;
        }
        
        
/**
         * Установить файл шаблона
         *
         * @param string $tpl
         */
        
public function assign($tpl) {
            
$this->template PATH'templates/'$tpl'.tpl';
            if (
file_exists($this->template)) {
                
$this->template file_get_contents($this->template);
                
$matches = array();
                
$count preg_match_all('/{row::([A-Za-z0-9]+)}(.*){\/row::/'$this->template$matches);
                if (
$count 0) {
                    for (
$i 0$i $count$i++) {
                        
$this->tblocks[$matches[1][$i]] = $matches[2][$i];
                    }
                    
$this->template preg_replace('/{row::([A-Za-z0-9]+)}(.+){\/row::([A-Za-z0-9]+)}\\n/i'''$this->template);
                }
            } else {
                echo 
'<small><b>Error.</b> Template <u>'.basename($this->template). '</u> is not exists!</small><br />';
                
$this->template '';
            }
        }
        
        
/**
         * Пропарсить шаблон
         *
         */
        
public function display($eval False) {
            if (
$this->template) {
                foreach (
$this->vars AS $var => $value) {
                    
$this->template str_replace('{'$var'}'$value$this->template);
                    if (empty(
$value)) {
                        
$this->template preg_replace('/{block::'$var'}(.+){\/block::'$var'}\\n/i'''$this->template);
                    } else {
                        
$this->template str_replace(array('{block::'$var'}''{/block::'$var'}'), ''$this->template);
                    }
                }
            
                if (
$eval) {
                    eval(
'?>'$this->template);
                } else {
                    echo 
$this->template;
                }
            }
            unset(
$this->vars);
            unset(
$this->tblocks);
            unset(
$this->template);
        }
    }
?>


Trieg 10.03.2010 16:14

я как раз почти закончил свой шаблонизатор, магу дать исходник... или даже переделать для работы с твоим двиглом но есть кое какие условия ($$ мя не интересуют)
PS: если ТС интересно то пиши в личку

AtomoS 10.03.2010 16:26

они может и от туда. по крайней мере мне это рано делать (по знаниям).
но это нужно - люди просят.

AtomoS 19.03.2010 10:36

Бьюсь с дминкой - нифига не получается(
хочет кто помочь? ссылка на архив в начале страницы..


Время: 15:08