Skip to content

Context

Understanding the context is crucial when working with Timber. Essentially, the context is an array of variables that is passed to your Twig template.

Local context variables are only available in the template where they are defined.

single.php
use Timber\Timber;
$context = Timber::context();
$context['message'] = 'This can be any variable you want';
$context['author'] = 'Tom';
Timber::render('templates/single.twig', $context);
{# views/templates/single.twig #}
<h3>Message by {{ author }}</h3>
<p>{{ message }}</p>

Each key added to $context becomes a variable in the Twig template. Call Timber::render() with the template path and the context array to pass the data through.

The global context is used for site wide data, like icons, ACF options page values, etc.

There are some special variables that are available by default.

site The site variable is a Timber\Site object which will make it easier for you to retrieve info about your WordPress site.

If you’re used to using blog_info( 'sitename' ) in PHP, you can use {{ site.name }} in Twig instead.

theme The theme variable is a Timber\Theme object and contains info about your theme.

user The user variable will be a Timber\User object if a user/visitor is currently logged in and otherwise it will be null.

To add your own data open up app/Hook/TimberHook.php and add your data to the addContext method.

app/Hook/TimberHook.php
public function addContext(array $context): array
{
$context['look_mom'] = 'No Hands!';
return $context;
}

ACFFieldsUtil provides two static methods for fetching options page fields. Both call get_fields('options') once and cache the result — subsequent calls in the same request return the cached array with no extra DB queries.

MethodUse when
getOptions()Fields that need ACF formatting (images → objects, relationships → posts, etc.)
getRawOptions()Fields containing raw HTML or scripts where ACF formatting would corrupt the output
app/Hook/TimberHook.php
use App\Util\ACFFieldsUtil;
public function addContext(array $context): array
{
$options = ACFFieldsUtil::getOptions();
$context['my_option'] = $options['my_option'] ?? null;
return $context;
}
// Outputting raw HTML stored in an options field (e.g. script tags)
use App\Util\ACFFieldsUtil;
$options = ACFFieldsUtil::getRawOptions();
echo $options['my_raw_html_field'] ?? '';

For adding custom Twig functions and filters, see the Twig guide.