In Symfony2, when trying to render index.mobile.twig, How would I load index.html.twig when index.mobile.twig doesn’t exist. instead go getting a “this template does not exist error”.
I believe the answer lies somewhere with creating a custom loader for Twig but I couldn’t find any documentation on it, just occasional references to it.
The answer involves extending the
twig.loader.classand creating an additional step once it’s discovered that the specific twig template doesn’t exist and before the Exception is thrown.PART 1 – Configuration
The answer involves extending the
twig.loader.class.Create a
customloader.phpwhich extends the TwigFilesystemLoaderfile.Modify your
config.ymlto include:parameters: twig.loader.class: Acme\YourBundle\Twig\Loader\name_of_your_classPART 2 – Extending the class
Extending the class is fairly straight forward.. The method I needed to modify was
findTemplate($template). It’s very small method and you could probably useparent::to extend the original code more properly.. However, I chose to completely over-write it and include the following code right before theUnable to find templateerror:After the code realizes that the file exists, it checks to see if
mobilewas the requested format. IF it is, it sets the format of the template object tohtmland then tries thename.html.twig. There’s a lot more you could do in this area but this solved my problem.