Прикручиваем php к tpl

Discussion in 'PHP' started by Fox_NICK, 19 Feb 2010.

  1. Fox_NICK

    Fox_NICK Elder - Старейшина

    Joined:
    10 Jan 2007
    Messages:
    45
    Likes Received:
    5
    Reputations:
    0
    опять же всем доброго времени суток!
    Столкнулся с таким вопросом

    имеется парсер

    PHP:
    <?php class parse_class     {     var $vars     = array();     var $template;      function get_tpl($tpl_name)       {       if(empty($tpl_name) || !file_exists($tpl_name))         {         return false;         }       else         {         $this->template  file_get_contents($tpl_name);         }       }     function set_tpl($key,$var)       {       $this->vars[$key] = $var;       }     function tpl_parse()       {       foreach($this->vars as $find => $replace)              {              $this->template str_replace($find$replace$this->template);              }       }     } $parse = new parse_class?>
    ну и index.php

    PHP:
    <?php  require('template.php'); $parse->get_tpl('Black/main.tpl'); $parse->tpl_parse();  print $parse->template;   ?>
    как сделать что бы пхп код отображался в корректном виде в файле *.tpl



    И еще один вопрос, хочу сделать так в cms dle
    тоесть задается переменная к примеру {online} и к ней присваивается фаил online.php и тогда в шаблоне просто указываем переменную {online} и отображается рабочий модуль)

    вотпробовал вот так:
    $parse->set_tpl('{online}','путь к модулю.php');

    ну и еще много чего пробовал, но не получилось, может кто нибудь знает как это реализовать?
     
  2. POS_troi

    POS_troi Elder - Старейшина

    Joined:
    1 Dec 2006
    Messages:
    1,569
    Likes Received:
    466
    Reputations:
    108
    И не будет

    Ты должен передать информацию из модуля в {online} а не путь к модулю.

    Допустим есть модуль online.php и в нем функция get_online(){...}

    Ты должен подключить данный модуль через Инклуд а в $parse->set_tpl('{online}','путь к модулю.php'); передать не путь к модулю а функцию get_online()

    Извиняюсь за несвязанную речь - спать хо =)
     
  3. Fox_NICK

    Fox_NICK Elder - Старейшина

    Joined:
    10 Jan 2007
    Messages:
    45
    Likes Received:
    5
    Reputations:
    0
    такс по идеи подключать так: Include ("$online.php");
    если я правильно понял вашу мысль.

    строго не судите, за пхп взялся 3-и дня назад))
     
  4. POS_troi

    POS_troi Elder - Старейшина

    Joined:
    1 Dec 2006
    Messages:
    1,569
    Likes Received:
    466
    Reputations:
    108
    include("online.php");
     
  5. Nelzone

    Nelzone Banned

    Joined:
    12 Apr 2008
    Messages:
    172
    Likes Received:
    134
    Reputations:
    6
    в 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);
        }
    }
    ?>
    я правильно понел?
     
    #5 Nelzone, 20 Feb 2010
    Last edited: 14 Jun 2010
    2 people like this.
  6. Fox_NICK

    Fox_NICK Elder - Старейшина

    Joined:
    10 Jan 2007
    Messages:
    45
    Likes Received:
    5
    Reputations:
    0
    Все да правильно! Всем спасибо огромное