Templating
I’ve been spending quite a couple of hours lately getting my new template engine to work. This piece of software, written in PHP (naturally), takes HTML templates and has the ability to substitute variables in that page, include other files in it, and hide or replicate sections of code (blocks). The positive upshot of this is that it allows you to keep the PHP and HTML code for a website as good as completely separated, which keeps both PHP and HTML clean and easy to modify something.
However, writing a template engine is everything except easy. I attempted it once before but gave up after having wasted lots of hours, but I finally decided to have another go. There’s a lot of pretty complex string parsing going on, and especially including other templates is a major pain in the ass. It can take forever to debug issues (such as pieces of HTML showing up in completely the wrong location). One bug that kept me busy in particular just added code to a template for no apparant reason. After long searching I finally found that the problem was the function that actually reads the files, which wasn’t cleaning up its buffer. And all that for a total of 23 kilobytes of code.
The engine works pretty smoothly though. Unlike many other template engines it does not make use of slow, complex and resource-intensive regular expressions. Not a single one. The result: 13 milliseconds average parsing time and 0.1 millisecond processing time, using a simple test template (that does use every feature the engine has several times over).
For the moment I’m using this for a litl’ project, but some time I might share the engine with the rest of the world.
Comments
Leave a Reply
