ExpressionEngine’s global variables are your friends

Often during ExpressionEngine development you’ll find yourself typing the same thing repeatedly in templates.  Or you have lack certain path information to finalize parts of your code. 

Global variables to the rescue.

ExpressionEngine’s global variables are simple to use.  Go to Templates—> Global variables.  For each one you’ll enter the variable name and its value.  I like to follow a convention of all lowercase words separated by dashes, for example, site-with-index.

Good cases for global variables:

  1. When you refer to a URL or path repeatedly. For example, perhaps you want to create Google map links for certain addresses listed on your web site.  Try this: put the following URL in to a global variable called google-map-url.

    http://maps.google.com/maps?f=q&hl=en&geocode=&q=

    Now in your code, to generate a map, you only need to recall the variable with {google-map-url}, and append something like the following to it:

    {address-1}+{city}+WI+{zip}
  2. Paths to scripts.  If you’re calling a script in different spots from your templates, replace the URL with a variable.
  3. Basic site information.  For example, for each ExpressionEngine site I create, I always create a variable called EE Developer.  Any time I need to refer to the site’s name, I just output the variable.  Now if your clients ask you to change their name from Bob’s Widgets, LLC to Bob’s Widgets, Inc., you just change the variable’s value.
  4. Snippets of HTML.  Maybe you need to output a piece of code that points elsewhere, like a little Flash widget.  You can drop this code in a global variable and output it anywhere.  An alternative to this method is to put it in a template and call it with {embed=“template_group/template_name”}.
  5. Anything else you need to re-use.