Twig is a must-have tool for any PHP developer. It's a powerful templating engine that allows you to leave the HTML out of your back-end code, and put it where it belongs - in the template files. It's particularly handy if you're working alongside a front-end developer, as you can work in parallel. Caching helps to keep everything running quickly.
This guide is a quick introduction to using Twig in your projects. If you've never used a templating engine before or you're a seasoned pro, this guide will get you up and running with Twig. Once you've started using it, you can't go back.
It's a good idea to start with the introduction first. This gets you the Twig download and some setup instructions.
A Quick Example
Here's a quick way to build a simple navigation bar with Twig. First, the template file:
This is going to loop through a list of links and display them, or show an apologetic message if there are no links.
Now for the PHP:
After setting up Twig, this simply builds an array of links and sends the data to the parser.
Changes Not Showing Up?
Twig includes built-in caching, which is worth turning on for the performance boost. You'll need to remember to delete the files from the cache folder when putting changes live though, or you'll see the cached templates.
If you don't want to keep clearing the cache folder while building a new page, just disable caching on your development site. You can disable the cache by setting the "cache" value in the array to false. The PHP example included above includes caching, albeit with a path that you will need to fill in.
There is a lot you can do with Twig. We may come back to this topic in the future.
Photo by Nrbelex