Hello to all! PHP has been studying for a long time, so I switched to templates. There was such a question on code optimization. I have a template and the template engine itself, as well as the main page.

Here is the template engine:

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

here is the template

 <html> <head> <title>{title}</title> <meta charset="utf-8"> </head> <body> {content} </body> 

Actually the question is: is it possible to somehow optimize the following code so as not to write the same functions many times:

  $parse->set_tpl('{title}','Заголовок сайта'); $parse->set_tpl('{content}','Контент сайта'); 

Thank you in advance!

  • one
    First, remove the brackets from the set_tpl and transfer them to tpl_parse so that it is str_replace('{'.$find.'}', ... you know for sure that these values ​​are parsed, so why should we create problems in the transfer of names? the second can be passed to set_tpl associative array - key value: set_tpl(['title'=>'заголовок', 'content' => 'контент']) , and in the function you can run through it and put everything in $this->vars - Alexey Shimansky

2 answers 2

This is not a template engine. And the typical misconception of all novice template makers.

In real life this will not work.

Because the real content does not consist of the line "site content". In fact, it consists of hundreds of stock clean as a tear HTML.

And if we sculpt all this HTML in the script code, then of course, we are not talking about any use of templates.

I recommend to check any ideas on at least minimally approximated to real life examples.

And after such a check, take the next step of all template makers - write a wrapper over the include, like

 public function render($template, $data) { extract ($data); include $template; } 

This in real life will also not be enough, but this template engine, at least minimally, can be called such, allowing you to separate the application logic from the display logic.

  • can you tell me more about extract, as I understand the variables to use to write to them just the same hundreds of lines of HTML code? - Nikita
  • No, in the received variables it is necessary to record the variables transferred from to the template engine. But the $ template file should be a PHP file in which these variables are output, as usual, <?=$title?> - Ipatiev
  • For practice, I recommend writing a template for displaying guestbook messages. So that HTML is present only in the template. - Ipatiev

Thanks to Alexey for the comment. Sat down, figured out, that's what eventually happened:

Template engine:

 <?php class pattern // Создаем класс шаблонизатора. { public $template; // Переменная, в которую запишем оригинальный шаблон, а затем модифицированый. function get_tpl($tpl_name) // Получаем файл шаблона. { if(!empty($tpl_name) || file_exists($tpl_name)) $this->template = file_get_contents($tpl_name); // Проверяем // Проверим, есть ли файл шаблона и не пустой ли он. else return false; // В противном случае вернем false. } function tpl_construct($dataarr) // "Построение" шаблона. { foreach($dataarr as $key => $value) $this->template = str_replace($key, $value, $this->template); // Через foreach заменяем все значения в шаблоне на значения, полученные из массива. } } ?> 

And the page itself:

 <?php require('./templates/pattern.class.php'); // Подгружаем шаблонизатор. $pattern = new pattern; // Создаем объект шаблонизатора. $pattern->get_tpl('./templates/default/template.tpl'); // Указываем путь к файлу шаблона. // Массив с данными. $data = array ( "{title}" => "заголовок", "{content}" => "контент", ); $pattern->tpl_construct($data); // Меняем значения в шаблоне на значения в массиве. print $pattern->template; // Отображаем страницу. ?>