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:

twig:
  globals:
     google_analytics_id: "UA-XXXXX-X"
     google_analytics_domain: "www.belchamber.us"

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

 <p>Google Analytics ID is: {{ google_analytics_id }}</p>

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
http://www.belchamber.us
http://www.aaronbelchamber.com

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

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