Setting Twig Global values in your Symfony system decouples hardcoding values like Google Analytics IDs

Here’s a handy trick to define things like your Google Analytics ID and domain on a global level then be able to call on those global variables in any Twig template.  This allows you to put unique values, usernames, etc in your config files and even different values in different environments like config_dev.yml.

Here’s a quick demonstration.  In config.yml file (your production environment) twig declare your globals:

Then in your Twig, call on these globals like so:

Keep in mind “google_analytics_id” can be any variable name you want.  To learn more, visit Symfony’s Twig Reference page.  This was a great tip that helps keep your global values separate from your code, this decoupling and modular approach allows for quick changes and scalability later.

As you can see, injecting a list of global values into your Twig views is pretty easy and is exactly what Sensio Labs had in mind when it designed the Symfony framework — it’s supposed to help web developers develop business solutions faster because developers didn’t need to keep rebuilding the same tools to get the system to perform the tasks needed.
Aaron Belchamber

Aaron Belchamber has written 243 articles

Leave a Reply

Your email address will not be published. Required fields are marked *