Best way to use services into twig ? #50523
-
Hello everyone, I've a question for you, we have into our professional project several way to use services into Twig, some are into Twig config file with global, others with Twig Extensions. Each way to do it are described into the doc : So, I was asking myself, is there a best practice to do it ? In terms of performances put it globally and load everywhere with globals, it is bad ? Or there is lazy loading or something ? And for extensions should we put all the logic into it and return only twig templates ? To avoid logic into twig and keep front only to display data ? Have a nice day, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Docs:
I don't fully understand this line.
AFAIC I try not to use dynamic twig globals (i.e. globals using services) and extensions but pass all required data when rendering a template (the logic required to prepare template data is executed in dedicated factories, view model etc.). From my experience, in the end twig extensions are just overhead that needs to be maintained. |
Beta Was this translation helpful? Give feedback.
-
You can still use extentions but don't put any logical functions in them (services etc), instead make a new file that lazy load your logical functions that extends from "RuntimeExtensionInterface". Don't forget to register your "RuntimeExtension" in services.yaml as "twig.runtime" This will lazy load the functions that you call from twig files instead of letting symfony load every single extension before loading any page |
Beta Was this translation helpful? Give feedback.
You can still use extentions but don't put any logical functions in them (services etc), instead make a new file that lazy load your logical functions that extends from "RuntimeExtensionInterface". Don't forget to register your "RuntimeExtension" in services.yaml as "twig.runtime"
This will lazy load the functions that you call from twig files instead of letting symfony load every single extension before loading any page