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!
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:
{% if site.constants.local_dev == 1 %}
here the js I dont want to show on the live-version of the site {% endif %}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.
Most helpful comment
use constant() function for accessing WP_CONFIG vars .
constant('WP_LOCAL_DEV').will do the required for you.