7

I'm trying to build a simple config bootstrap for use in multi-server environments. I realise there are lots of config bootstraps around, but a lot of the popular ones seem a bit complicated for what I need (and feel comfortable with) at this stage. I'm currently using this for the database.php file.

I want to create a global variable (or another type of variable that can be used in the same way) inside the config.php file, and then be able to output it inside the templates - how would I go about doing this?

I've tried creating this and adding it to the config.php file:

$config['my_google_analytics_key'] = 'UA-XXXXXXX-XX';

But entering {my_google_analytics_key} inside my templates outputs {my_google_analytics_key} rather than UA-XXXXXXX-XX.

So I'm obviously going about this the wrong way, but I'm not sure what steps I'm missing. Thanks.

7

Take a look at your main index.php file, you should see this line:

//  $assign_to_config['global_vars'] = array(); // This array must be associative

Once that's uncommented and populated the variables should be available in your templates. For example:

$assign_to_config['global_vars'] = array('analytics_key' => 'UA-XXXXXXX-XX');

That should be available as {analytics_key} in any template.

If you'd prefer to set the variables in config.php you can, but you need to explicitly set the scope of the $assign_to_config variable:

global $assign_to_config;
$assign_to_config['global_vars'] = array(
    'analytics_key'  => 'UA-XXXXXXX-XX',
    'something_else' => 'ABC',
    'another_one'    => '12345'
);
  • Thanks for the answer, Dom. I would prefer to keep these in the config.php file, and that piece of code does the trick nicely. Out of interest, is it possible to add multiple variables using this method, one after the other? I tried, but only the last variable worked. – Stephen Apr 27 '13 at 16:25
  • 1
    No problem. You should be able to set an unlimited number of variables so long as you're populating the array correctly. I've updated my answer with some sample code. – Dom Stubbs Apr 27 '13 at 16:33
  • Thanks again for this, Dom. I was completely messing up the array when adding multiple variables previously, but I can't go wrong now. :-) – Stephen Apr 27 '13 at 17:24
0

Instead of using an array in index.php is possible to create Template variables inside the template as well.

Developer > Template Manager > Template Variables > Create New

Global Variables can contain text, HTML, javascript, etc. but cannot contain PHP code or ExpressionEngine tags ...

Refer to the official documentation here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.