Multiple Twig Template Folders with Slim Framework
This post is more for my own records than anything else as I couldn’t find this information anywhere on the internet.
I have a Slim Framework application that uses Twig for it’s templates. I wanted to initiate the Twig instance in my bootstrap file, but then to dynamically update the template directory within my class files depending on the request. It took me a while to figure out how to set Slim to look in multiple directories, or to change the template directory altogether, to render a view.
This method also lets you change the template directory after the Twig instance has been initiated.
First step is to make sure you have Slim, Slim-views and Twig installed through your
In your bootstrap file load your Twig views as normal:
With this setup Twig will only look in the
template folder for templates. My first attempt to change this was using Slim’s
setTemplatesDirectory() function. However this function only changes the Twig template if it is called before Twig is initialised; not what I wanted.
To change the template directory we will have to interact directly with the Twig instance:
I hope someone else finds this useful.
Noticed a typo or error in this post? Fork and edit it on Github!