Timber: Custom (constants) variables in Timber

Created on 8 Aug 2014  路  5Comments  路  Source: timber/timber

Hi Guys,

First of all, Timber is awesome, thanks for making this!
I would like to know if there is a way to use custom constant variables in Timber. For example, I have this custom constant WP_LOCAL_DEV set to true in my wp-config.php. Now I would access this constant in my layout.twig file, so I could use this with a statement to include certain pieces of code if my WP_LOCAL_DEV is set to true. Could there be a feature where I could do something like this:

Timber::$constants = array('local_dev' => WP_LOCAL_DEV);

so I can use this as the following:


{% if site.constants.local_dev == 1 %}
//hide this for production
{ endif }

Many thanks!

Most helpful comment

use constant() function for accessing WP_CONFIG vars .

constant('WP_LOCAL_DEV'). will do the required for you.

All 5 comments

I may not understand your question, but I think the easiest solution may be to pass it in to your view.

    $context = Timber::get_context();
    $context['local_dev'] = WP_LOCAL_DEV;
    $Timber::render('path-to-view.twig', $context);

Then in your view.

{% if local_dev == 1 %} //hide this for production { endif }

Indeed that's one way to give variables to a template, but I have two issues here:

  • How can I use in a constant into a layout? For example, with WP_LOCAL_DEV set to true (defined in my wp-config.php) I want to use this in my layout.twig (the file that will be used by views) so I can exclude scripts (for example browser sync): {% if site.constants.local_dev == 1 %} here the js I dont want to show on the live-version of the site {% endif %}
  • If I want to use this variable in a view, I'd rather not want to pass in WP_LOCAL_DEV in every view separately, that way it's not really reusable (especially if you use it in a file that's been used by other views)

I hope this clears it up a little!

You can use the timber_context filter in your functions.php to pass that in everywhere:

add_filter('timber_context', 'add_to_context');
function add_to_context($data){
  $data['local_dev'] = defined('WP_LOCAL_DEV') ? WP_LOCAL_DEV : true;
  return $data;
}

Then you can reference local_dev in your Twig views.

Thank you very much Nick, this works!

use constant() function for accessing WP_CONFIG vars .

constant('WP_LOCAL_DEV'). will do the required for you.

Was this page helpful?
0 / 5 - 0 ratings