Simple Standalone Template Engine
#1
Template engines are numerous on the web. Most applications opt for long-standing options such as Twig and Blade (or Smarty, Latte, among others). These are both robust and mature, containing almost any feature that could possibly ever be requested. They are ideal for a wide variety of use cases.

These engines are also quite large (and arguably suffer greatly from feature creep over the years). I was recently developing a lightweight website from scratch, and I already had an existing template engine that I had used repeatedly in the past. I ended up extending it and adding a few new features, and it wasn't long before I got carried away. I implemented (most) of the bare-essentials of larger engines and managed to squeeze it within around an ~8KB footprint. It is likely one of the most lightweight template engines ever made. 

Features: 
  • Full Template Inheritance Support (blocks/yields/extends, modeled similarly to Laravel/Blade)
  • Listeners/Events: MyBB-style plugin hooks directly in the templates! (Yes, really)
  • Template Loops
  • If / else if / else conditional statements
  • Virtually unlimited nesting support (unlike some other "skeleton" template engines)
  • Template includes/backreferences (Nested templates. Pointers also supported)
  • Language/locale management and dedicated lang strings. (No need to set language strings manually)
  • Autoescaping (anti-XSS)
  • Renders at native performance (Compiles/Caches templates to vanilla PHP) 
Downsides: 

With this being a tiny template engine, it relies on relatively simple syntax parsing and builds on top of various features already existent within the PHP language. It is powered primarily by recursive regex callbacks (a feature used in most BBcode parsing engines) to generate its compiled templates. While this is great for creating small and lightweight parsers (and can even handle deeply nested and complex structures), it doesn't generate very verbose output if severely malformed or unclosed template tags are present. Most big-name engines such as Twig resolve this by parsing with dedicated Lexers and Tokenizers instead. And it's for good reason, as the results are usually more reliable.

It's not much, but I figured I'd share for anyone who might find interest. It may come in handy for simple websites or otherwise low-overhead websites where a lightweight (but featured) engine is required. It can otherwise serve as an example of how these sorts of parsers work (in case anyone ever stumbles across this page from Google Toungue Wink

Github:  https://github.com/Darth-Apple/simple-ph...lates/wiki
Reply


Messages In This Thread
Simple Standalone Template Engine - by Darth Apple - 2021-01-29, 05:01 AM
RE: Simple Standalone Template Engine - by Laird - 2021-01-29, 05:50 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)