Всем привет. Подскажите как создать собственные шаблонные теги, типа вот такого <element name="news" count="10" template="mainpage" sort="date"> который говорит, что в данном месте необходимо вывести 10 новостей, отсортированных по дате по шаблону mainpage
Это вообще гониво какое то... нужент тебе строчный элемент - пиши span, нужен блочный - пиши div. Класс дал, css прописал вот тебе и свой тэг. Бред какой-то...
может не так задачу описал. Суть идет не про свой html-тег, а по то что при вставке такой конструкции в шаблоне, будут выводиться новости. Ну типа как в MODx [[*tvparam]], или {{BANNER}} в другом движке
я в своём PinPIE (всех уже от него тошнит, но) сделал теги нескольких типов. Совместными усилиями вместе с @[vs] мы родили вот такое чудо на регулярках: https://github.com/pinpie/pinpie/blob/stable/src/PP.php#L156 PHP: /** * Parses any string and executes found tags. Returns resulting content as string. * @param string $content * @param null $parent (optional) Parent tag can be provided. Rarely used outside PP class. * @return String */ public function parseString($content, $parent = null) { if (empty($parent)) { $this->tagPath[] = '/'; } else { $this->tagPath[] = $parent->type . $parent->name; } $content = preg_replace_callback(/** @lang RegExp */ '/ \[ ([^\[\]]*?) \[ ([!\d]*) ([@#$%=]?) (?!\*) ([^\[\]]+?) \] ([^\[\]]*?) \] (\r\n|\n\r|\r|\n)* /xsmuS', function ($matches) use ($parent) { /* defaults =) to prevent warning on last (enter)* detector */ $matches += ['', '', '', '', '', '', '']; /* creating tag from array of matches */ $tag = $this->createTag($matches, $parent); $tag->index = count($this->tags); $this->tags[] = $tag; /* render output */ $tag->output = $tag->getOutput(); if (!empty($tag->output)) { /* if tag output is not empty - add line endings to make tags with line endings just after tag have its output have new line chars. And tags without new line chars after tags will be replaced only with its output. */ $tag->output .= $matches[6]; } /* set time for debug */ $tag->time['end'] = microtime(true); $tag->time['total'] = $tag->time['end'] - $tag->time['start']; /* return tag output so it will replace tag in the text with its output */ return $tag->output; } , $content); array_pop($this->tagPath); return $content; } она дёргает вот это: PHP: protected function createTag($matches, $parent) { /* $matches * Tag with new line after tag array (size=8) 0 => string '[header[!$snippet]template] ' (length=28) <-- New line 1 => string 'header' (length=6) <-- placeholder to put tag output in 2 => string '!' (length=1) <-- cache forever 3 => string '$' (length=1) <-- it is snippet 4 => string 'snippet' (length=7) <-- snippet name 5 => string 'template' (length=8) <-- template 6 => string ' ' (length=1) <-- New line */ $fulltag = $matches[0]; $type = $matches[3]; $placeholder = ($matches[1] == '' ? false : $matches[1]); $template = ($matches[5] == '' ? false : $matches[5]); if ($matches[2] === '!') { $cachetime = $this->conf->pinpie['cache forever time']; } else { $cachetime = ($matches[2] == '' ? 0 : (int)$matches[2]); } $fullname = $matches[4]; $tagClass = '\pinpie\pinpie\Tags\Tag'; if (isset($this->conf->tags[$type])) { $tagClass = $this->conf->tags[$type]['class']; } $tagSettings = []; if (!empty($this->conf->tags[$type])) { $tagSettings = $this->conf->tags[$type]; } $priority = 10000; $depth = 0; if (!empty($parent)) { $priority = $parent->priority; $depth = $parent->depth + 1; } $tag = new $tagClass($this, $tagSettings, $fulltag, $type, $placeholder, $template, $cachetime, $fullname, $parent, $priority, $depth); return $tag; }
Это давно реализовано в стандарте XHTML и это перспективное будущее развития веб компонентов Возьмите готовый шаблонизатор Twig, Smarty, mustache
суть тут простая. есть регулярка Код (Text): / \[ ([^\[\]]*?) \[ ([!\d]*) ([@#$%=]?) (?!\*) ([^\[\]]+?) \] ([^\[\]]*?) \] (\r\n|\n\r|\r|\n)* /xsmuS она ищет квадратные скобочки и то что в них. У меня относительно сложный синтаксис, она может быть куда проще. Но короче она находит текст в квадратных скобочках. И всё. Потом этот текст кидается в функцию. Например https://regex101.com/r/4LOfQC/1 Код (Text): / {{ ([^}]+) }} /xsmu x флаг это чтобы регулярку можно было писать в несколько строк и с комментариями даже остальные флаги это юникод и многострочность. Т.е. даннаря регулярка находит текст в таких вот скобочках даже если он занимает несколько строк
Вспомнил и я баловался. (Кто не писал свой мега шаблонизатор) Так вот брал я стандартные HTML комментарии и их парсил PHP: public function render($viewFile, array $params = []) { extract($params, EXTR_SKIP); ob_start(); include($viewFile); $this->content = preg_replace_callback('/(<!--{(.+?)}-->)/', [$this, 'fetch'], ob_get_clean()); }
На сколько я понял, тут речь идёт вообще о патернах, типа как на DLE. То есть обработка файлов tpl. Или можно просто прогонять всю страницу через str_replace (), например, str_replace ("%TIME%", "time ()", $mypage); Или я не то понял?