Custom Global Variables Using the Config File
One thing I like to do is take advantage of global_vars
in template tags. I’m a big fan of keeping configuration in the site’s config.php
file. That way, values can be changed depending on the environment either by using something like Ansible to provision and configure your site, or by using PHP’s getenv()
functions. For additional reading on environment based configuration check out The Twelve-Factor App.
Here is an example of what is included in nearly all of my ExpressionEngine site’s config.php
files. Each variable is prefixed with global:
, similar to how we prefix the pre:
variables in my previous article.
global $assign_to_config;
$default_global_vars = [
'global:disabled_params' => 'disable="trackbacks|pagination|member_data"',
'global:disabled_params_all' => 'disable="trackbacks|pagination|member_data|category_fields|categories|custom_fields"',
'global:disabled_params_strict' => 'disable="trackbacks|pagination|member_data|category_fields|categories"',
'global:blog_category_groups' => '2|3|5|6',
'global:some_api_key' => '98ufahaskdfnasd312',
];
if (!isset($assign_to_config['global_vars'])) {
$assign_to_config['global_vars'] = [];
}
$assign_to_config['global_vars'] = array_merge(
$default_global_vars,
$assign_to_config['global_vars']
);
Now in my templates I can shorten my tags, and globally update every entries tag on the site with a single change in the config.php
file.
{exp:channel:entries {global:disabled_params}}
...
{/exp:channel:entries}
Some people like to prefix everything. I’ve seen custom fields prefixed with cf_
, thus their templates are filled with {cf_body}
, {cf_summary}
, or {cf_related_entries}
. I’ve personally never been a fan of prefixing field variables unless it is a prefix which helps indicate what channel it belongs to, such as {person_first_name}
. {cf_person_first_name}
feels redundant to me, but again, that is personal preference.
Prefixing or no prefixing, find what works for you, just pick a pattern and be consistent 😊
Comments 2
pixi
Thank you for this interesting article Brian.
May I suggest you a topic for a future article on the same subject? A “how-to” to natively store a custom data from a channel field into a global variable to be used as an early parsed tag parameter. Without using preload replace etc…(Maybe there is no way, don’t know).
Sobral
There’s a way, @pixi. Using embeds.