PHP - Creating a custom template system?

I already searched here, and, surprisingly, I did not find the answer. I found one similar thread, but there is no real solution. The hard part is a loop, if I don't need a loop, I could just do a regular replacement.

So, I have a .html file with some markup, for example:

<ul> {{startloop}} <li> <img src="/album/{{filename}}" alt=""> <span>{{imgname}}</span> </li> {{endLoop}} </ul> 

What I want to do is replace {{filename}} and {{imgname}} with something else. I know how to do this, but the fact is that I want it inside the loop. Therefore, for each looping element, {{filename}} and {{imgname}} will be different. If I have two "elements", it will look like this (example):

 <ul> <li> <img src="/album/image1.jpg" alt=""> <span>Test name 1</span> </li> <li> <img src="/album/image2.jpg" alt=""> <span>Test name 2</span> </li> </ul> 

Any suggestions?

+4
source share
6 answers

For a long time I was a big fan of the "smart" template engine until I realized that I did not need it at all :) This is much better and faster for users of direct built-in php tags.

just put html + php_tags in the file 'some_template.inc' instead of the html file.

then show this template with "include ('template.inc');"

example 'template.inc':

 <ul> <?foreach ($items as $item){?> <li> <img src="/album/<?=$item[filename]?>" alt=""> <span><?=$item[imgname]?></span> </li> <?}?> </ul> 

+2
source

Do not create a parser as completely meaningless, PHP is already a template engine, all you want to do is expand its capabilities with an encapsulated template system.

Below is the way that I always create my template engine, I lose it very much and can be expanded with the help of template assistants as such.

The good thing about my template system is that you don’t have to spend your resources creating a caching system for compiled templates, as they are already in a compiled state, compared to engines like smarty.

First, we want to create a basic template class that will be used to set data, select a template, etc.

So let's start with this:

 class Template { private $__data = array(); public function __construct(){/*Set up template root here*/} public function __set($key,$val) { $this->__data[$key] => $val; } public function __get($key) { return $this->__data[$key]; } public function Display($Template) { new TemplatePage($Template,$this->__data); //Send data and template name to encapsulated object } } 

this is a very simple class that will allow you to do something like

 $Template = new Template(); $Template->Userdata = $User->GetUserData(); $Template->Display("frontend/index"); 

Now you might notice the class above called TemplatePage , this is the class that loads the actual file template, and inside the actual template you fall into the TemplatePage area.

This will allow you to have methods for retrieving your template data and accessing helpers, below is an example of TemplatePage

 class TemplatePage { private $__data = array(); public function __construct($template,$data) { $this->__data = $data; unset($data); //Load the templates if(file_exists(TEMPLATE_PATH . "/" . $template . ".php")) { require_once TEMPLATE_PATH . "/" . $template . ".php"; return; } trigger_error("Template does not exists",E_USER_ERROR); } public function __get($key) { return $this->__data[$key]; } public function require($template) { if(file_exists(TEMPLATE_PATH . "/" . $template . ".php")) { require_once TEMPLATE_PATH . "/" . $template . ".php"; return; } trigger_error("Template does not exists",E_USER_NOTICE); } public function link($link,$title) { return sprintf('<a href="%s">%s</a>',$link,$title); } } 

So now that the template is loaded into the scope of the class, you can extend methods like link and require to have a fully functional set of template tools

Template example:

 <?php $this->require("folder/js_modules") ?> <ul> <?php foreach ($this->photos as $photo): ?> <li> <?php echo $this->link($photo->link,"click to view") ?> <span><?php echo $photo->image_name?></span> </li> <?php endforeach; ?> </ul> <?php $this->require("folder/footer") ?> 
+2
source

Is there a reason you are creating your own template system? I would recommend using Smarty http://www.smarty.net/

It already has this feature, as well as much more, such as caching, etc.

0
source

It might be best to use MVC / MVVVM templates here, and then you will get it for free along with a very structured and organized code project.

Take a look at this page from the Rasmus blog as a tutorial for this workflow: http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html

If you're ready to let the rules go a bit, Zend is very good as a framework and can help you build your site quickly. This saves you from having to rewrite a lot of code yourself and provide you with some additional features that you probably won't have to write yourself.

I completely agree with you regarding the size of some frameworks, and you can do it without them. Compromise is time. Coding time and debugging time. As I said, if you are ready to let go of some control, you can break through your project, dealing only with debugging the "business logic" of your site and not invent a lot of existing code.

Hope this will be helpful.

0
source

The only way to create a super-fast template system is to rely on PHP as a parser or to use extensions encoded in C. In addition, in any case, there is probably no reason to try to do this, as it has already been done thousands of times. There are many big winners like Smarty, although the performance is not stellar. The template system in PHPBB is also very good (using pre-analysis and PHP caching). Avoid reinventing the wheel here.

If performance is a serious issue, I recommend Blitz .

Borrowing from PHPBB is another route. If you do not have access to the PHP extension on your server, and Smarty is not your cup of tea in a performance format, and you would like all open-source code you could do as I did and wrest what in PHPBB . This is not a final decision, full of details, but it is not bad - and with the source you can customize it to taste. It eval for code supports a certain level of expressions and supports HTML comment tags as an escapes / markers template, which is convenient for less technical designers.

0
source

Replace {{tags}} with chunks of php code ( foreach in this case) and then the eval result. This is how php template engines work.

Example:

 $template = "<h1>Hello {{name}}</h1>"; $name = "Joe"; $compiled_template = preg_replace( '~{{(.+?)}}~', '<?php echo $$1 ?>', $template); eval('?>' . $compiled_template); 

prints <h1>Hello Joe</h1>

A more advanced example involving arrays and loops

 $template = " {{each user}} {{name}} {{age}}<br> {{end}} "; $user = array( array('name' => 'Joe', 'age' => 20), array('name' => 'Bill', 'age' => 30), array('name' => 'Linda', 'age' => 40), ); $t = $template; $t = preg_replace( '~{{each (\w+)}}~', '<?php foreach($$1 as $item) { ?>', $t); $t = preg_replace( '~{{end}}~', '<?php } ?>', $t); $t = preg_replace( '~{{(\w+)}}~', '<?php echo htmlspecialchars($item["$1"]) ?>', $t); eval('?>' . $t); 

In response to other comments telling me that “php is a template engine” and “eval is evil” are people, don’t repeat the stupid mantras you heard somewhere. Try to think for yourself.

-3
source

All Articles