PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, March 12, 2022

[FIXED] Change Twig Loader order

 March 12, 2022     php, symfony, symfony6, twig     No comments   

Issue

So I've created a few twig loaders in my project for templates stored in databases. Simply having them implement LoaderInterface already automatically adds them to the default Twig\Loader\ChainLoader - however, I haven't found a way to configure the order.

When I check which loaders are in the ChainLoader, it's

LoaderA -> LoaderB -> FilesystemLoader

, but I want the order to be

FilesystemLoader -> LoaderB -> LoaderA

If I define twig.loader in my services.yaml, it always ends up with infinite recursion and nothing works. If I manually configure the calls to twig.loader.chain, I get the correct order of loaders, followed by a chainloader X, followed by the loaders in the "autoconfigured" order. Chainloader X is the same as the very ChainLoader Symfony configures, so... infinite recursion if a template is not found.

So how on earth do I tell twig which loaders to load in what order? Do I need to create a CompilerPass just for this simple requirement?


Solution

You can alter the order by tagging the services manually, when priority is not specified it defaults to 0:

# services.yaml
    App\Twig\LoaderA:
        tags:
            - { name: 'twig.loader', priority: 2 }
    App\Twig\LoaderB:
        tags:
            - { name: 'twig.loader', priority: 1 }

If you prefer, since Symfony 5.3 (running under PHP 8), you can use PHP attributes instead.



Answered By - msg
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing