Antichat снова доступен.
Форум Antichat (Античат) возвращается и снова открыт для пользователей.
Здесь обсуждаются безопасность, программирование, технологии и многое другое.
Сообщество снова собирается вместе.
Новый адрес: forum.antichat.xyz
 |
|

11.06.2008, 21:57
|
|
Постоянный
Регистрация: 11.11.2006
Сообщений: 834
Провел на форуме: 3941248
Репутация:
668
|
|
Шаблонизаторы..
Вот хотел послушать гениальные идеи людей по шаблонизаторам
я например написал так...
например в шаблоне
Код:
<----START NEWS HERE---->
{NEWS}
<----END NEWS HERE---->
а в скрипте идёт
PHP код:
$where[0] = '<----START NEWS HERE---->';
$where[1] = '<----END NEWS HERE---->';
$what['{NEWS}'] = $news;
$tpl = $templ->templ($where,$what);
бла бла
echo $tpl;
надеюсь вы примерно поняли как это работает...=)
в некоторых случьях это бывает удобно ...
но всёже по мне это ужасная реализация шаблонов..
может у вас есть светлые идеи?=)
|
|
|

11.06.2008, 23:38
|
|
Участник форума
Регистрация: 25.03.2008
Сообщений: 138
Провел на форуме: 1105166
Репутация:
201
|
|
А почему ужасная?
PHP код:
$where[0] = '<----START NEWS HERE---->';
$where[1] = '<----END NEWS HERE---->';
По мойму даже очень ужобно 
|
|
|

11.06.2008, 23:47
|
|
Участник форума
Регистрация: 06.06.2008
Сообщений: 162
Провел на форуме: 3942177
Репутация:
244
|
|
Я в большинетсве случаев делаю так:
header.php:
PHP код:
<html>
<head>
<title>MySite - {title}</title>
<link rel="alternate" type="application/rss+xml" title="RSS - {rsstitle}" href="/services/rss/rss{rss}.php">
</head></html>
и затем:
index.php
PHP код:
$temaplate = file_get_contents('header.php');
function parse($template, $assigned=array())
{
foreach( $assigned as $word => $replace)
{
$template = preg_replace( "/\{$word\}/i", "$replace", $template );
}
return $template;
}
$title = 'Главная страница';
$header = parse($temaplate, array('title' => $title,
'rss' => 'test'));
echo $header;
|
|
|

11.06.2008, 23:51
|
|
Постоянный
Регистрация: 16.02.2008
Сообщений: 724
Провел на форуме: 1025839
Репутация:
581
|
|
Все хорошо, но зачем придумывать велосипед? Смотря под какие цели нужен шаблонизатор и что он должен уметь.
Если просто заменять вариэйблы тогда пойдет...
|
|
|

11.06.2008, 23:53
|
|
Познавший АНТИЧАТ
Регистрация: 02.06.2006
Сообщений: 1,188
Провел на форуме: 6023777
Репутация:
2642
|
|
Кому интересно, вот мой пост по этой теме:
https://forum.antichat.ru/showpost.php?p=665776&postcount=23
|
|
|

11.06.2008, 23:56
|
|
Постоянный
Регистрация: 11.11.2006
Сообщений: 834
Провел на форуме: 3941248
Репутация:
668
|
|
Не удобно в том плане что если шаблон большой то пол шаблона это
<---blabla start ---->
<---blabla end---->
<---blabla start ---->
<---blabla end---->
etc...
и как сделать так тоб пхп код в шаблоне не исполнялся?
|
|
|

12.06.2008, 00:07
|
|
Постоянный
Регистрация: 11.11.2006
Сообщений: 834
Провел на форуме: 3941248
Репутация:
668
|
|
NOmeR1
Твой способ помойму немного не удобен т.к я например использовать цикл части шаблона
например
Код:
<---TEMPLATE START--->
тут шапка
<---NEWS START--->
<tr><td>
{NEWS}
</td</tr
<---NEWS END--->
фоот
<---TEMPLATE END--->
а в файле могу сделать так
PHP код:
$where[0] = '<---TEMPLATE START--->';
$where[1] = '<---NEWS START--->';
$tpl = $templ->templ($where,0);
$where[0] = '<---NEWS START--->';
$where[1] = '<---NEWS END--->';
запрос..
while ($news = mysql_fetch_assoc($result))
{
$what['{NEWS}'] = $news['content'];
$tpl .=$templ->templ($where,$what);
}
а тут добовляем ещё и фоот
echo $tpl;
|
|
|

12.06.2008, 00:30
|
|
Участник форума
Регистрация: 11.05.2007
Сообщений: 149
Провел на форуме: 6373157
Репутация:
247
|
|
Вот такой простенький шаблонизатор юзаю я
yuactpl.php
PHP код:
<?
if(!class_exists("yuactpl"))
{
class yuactpl
{
var $tpls=array();
var $ptpls=array(); //parsed templates
var $wtpls=array(); //while templates (blocks, used many times)
var $pwtpls=array(); //parsed while templates
//**
function file2string($file)
{
if (file_get_contents($file))
{
return file_get_contents($file);
}
else
{
return false;
}
/*
if(file_exists($file) && is_readable($file))
{
$f=fopen($file,"rb");
$filecontent=fread($f,filesize($file));
fclose($f);
return $filecontent;
}else
{
return false;
}
*/
}
//**
function loadtpl($tpl)
{
if($result=$this->file2string($tpl))
{
$this->tpls[$tpl]=preg_replace_callback('/\<script language="php"\>(.*)\<\/script\>/isU',create_function('$data','return eval($data[1]);'),$result);
return true;
}
return false;
}
//**
function parse($rarray,$tpl) //replace array ( array('title' => 'Welcome', 'body' => 'This is an example',) )
{
if(!isset($this->tpls[$tpl]) or !is_array($rarray)) return false;
//**
$tpltxt/*template text*/=$this->tpls[$tpl];
//**
foreach($rarray as $key=>$value)
{
if(!is_array($value)) $tpltxt=str_replace('{'.$key.'}', $value, $tpltxt);
}
//**
$this->ptpls[$tpl]=$tpltxt;
return true;
}
//**
function getparsedtext($tpl)
{
if(!isset($this->ptpls[$tpl])) return false;
//**
return $this->ptpls[$tpl];
}
//**
function loadwtpl($tpl,$delimiter="<!--delimiter-->")
{
if($result=$this->file2string($tpl))
{
$this->wtpls[$tpl]=explode($delimiter, preg_replace_callback('/\<php\>(.*)\<\/php\>/isU',create_function('$data','return eval($data[1]);'),$result));
return true;
}
return false;
}
//**
function wparse($rarray,$tpl,$n) //replace array ( array('title' => 'Welcome', 'body' => 'This is an example',) )
{
if(!isset($this->wtpls[$tpl][$n]) or !is_array($rarray)) return false;
//**
$tpltxt/*template text*/=$this->wtpls[$tpl][$n];
//**
foreach($rarray as $key=>$value)
{
if(!is_array($value)) $tpltxt=str_replace('{'.$key.'}', $value, $tpltxt);
}
//**
$this->pwtpls[$tpl][$n]=$tpltxt;
return true;
}
//**
function wparseall($rarray,$tpl)
{
if(!isset($this->wtpls[$tpl]) or !is_array($rarray)) return false;
//**
foreach($rarray as $key=>$value)
{
$this->wtpls[$tpl]=str_replace('{'.$key.'}', $value, $this->wtpls[$tpl]);
}
//**
return true;
}
//**
function getwparsedtext($tpl,$n)
{
if(!isset($this->pwtpls[$tpl][$n])) return false;
//**
return $this->pwtpls[$tpl][$n];
}
//**
function fastparse($tpl,$rarray=array(),$echo=true)
{
if(!isset($this->tpls[$tpl])) $this->loadtpl($tpl);
$this->parse($rarray,$tpl);
if($echo) echo $this->getparsedtext($tpl);
else return $this->getparsedtext($tpl);
}
//**
function fastwparse($tpl,$rarray=array(),$num=0,$echo=true)
{
if(!isset($this->wtpls[$tpl])) $this->loadwtpl($tpl);
$this->wparse($rarray,$tpl,$num);
if($echo) echo $this->getwparsedtext($tpl,$num);
else return $this->getwparsedtext($tpl,$num);
}
}
}
?>
index.php
PHP код:
<?php
include('yuactpl.php');
$title = "blabla" // допустим выбирается с БД
$content = "привет. я задрот...." // тоже с БД
$tp = new yuactpl;
$template = "./index.tpl";
$page_data = array(
'title' => $title,
'content' => $content
);
$tp->fastwparse($template, $page_data);
?>
index.tpl
Код HTML:
<html>
<head><title>{title}</title>
<meta http-equiv="content-type" content="text/html; charset=utf8"/>
</head>
<body>
{content}
</body>
</html>
Быстрый и удобный
PS
Ещё есть возможность использовать в шаблоне php код:
в тегах пишется
Код HTML:
<script language="php">echo "bla"</script>
Если интересно, почитайте http://forum.dklab.ru/viewtopic.php?p=38883
Последний раз редактировалось n3m0; 12.06.2008 в 00:35..
|
|
|

27.06.2008, 16:55
|
|
Познавший АНТИЧАТ
Регистрация: 02.06.2006
Сообщений: 1,188
Провел на форуме: 6023777
Репутация:
2642
|
|
Вот - если кому интересно, сделал скрипт по этой теме, что-то вроде "системы" {if выражение}утверждение{/if}
Вот к примеру у нас есть массивы
Код:
$true = array(true, false, true, false);
$false = array(false, true, false, true);
И файл с шаблоном
Код:
1
{if $true[0] == false}2{/if}
{if $true[1] == $false[0]}3
{if false == $true[2]}8{/if}
5{/if}
{if false === $false[0]}
{if $true[0] == $false[0]}6{/if}
7
{if $true[1] == $false[3]}
8
{/if}
{/if}
9
Ну и сам скрипт
Код:
<?php
function format_eval($matches) {
$exp = preg_replace('~\$((?![0-9])[a-zA-Z0-9_\x7F-\xFF]+)~', '$GLOBALS[\'\\1\']', $matches[1]);
$txt = var_export($matches[2], true);
eval('$string = ('.$exp.') ? '.$txt.' : NULL;');
return $string;
}
$text = file_get_content('template.html'); // template.html - файл с шаблоном
$pattern = '~{if (.+)}(((?>(?R)|(((?!{if .+})|{/if})).+)+)+){/if}~isU';
while(preg_match_all($pattern, $text, $matches)) {
$text = preg_replace_callback($pattern, 'format_eval', $text);
}
echo $text;
?>
Вывод:
|
|
|

27.06.2008, 17:10
|
|
Постоянный
Регистрация: 30.12.2006
Сообщений: 434
Провел на форуме: 849583
Репутация:
210
|
|
Вот - если кому интересно, сделал скрипт по этой теме, что-то вроде "системы" {if выражение}утверждение{/if}
Еще чуть-чуть и к Smarty придем 
|
|
|
|
 |
|
Похожие темы
|
| Тема |
Автор |
Раздел |
Ответов |
Последнее сообщение |
|
Шаблонизаторы
|
Дикс |
PHP, PERL, MySQL, JavaScript |
8 |
09.01.2008 23:28 |
|
Здесь присутствуют: 1 (пользователей: 0 , гостей: 1)
|
|
|
|