Skip to content
This repository has been archived by the owner on Jun 28, 2023. It is now read-only.

Adding data context to a template

Koen edited this page Aug 1, 2019 · 5 revisions

Each Twig template can access a global context. This context is added when the initial Twig template is rendered.

Adding data to a single template

If you only need to add data to a single template (and all templates rendered by that template), you can add it to the context in the PHP file rendering that template.

Example #1

In archives.php, we're using pagination for all archives, except the example post type. We'll show all posts without any limit:

$context = Timber::get_context();

if (is_post_type_archive('example')) {
    $context['posts'] = new Timber\PostQuery([
        'post_type' => 'example',
        'posts_per_pages' => -1,
    ]);
} else {
    $context['posts'] = new Timber\PostQuery();
}

Timber::render('base.twig', $context);

Example #2

In template-example.php, we're adding a specials variable with an array of special posts from the example post type.

$context = Timber::get_context();
$context['specials'] = (new PostTypes\Example)->fetch_special_examples();
Timber::render('base.twig', $context);

Adding data to all templates

The global context can be seen in Grrr\Theme\Setup. You can add data there, which will make it available to all templates.

Limiting context in a template/partial

If you want to limit data in a template, you can render it with the only attribute. This can be good since a lot of simple partials don't need access to the global context, and can be rendered with simple arguments:

{% include 'partials/page-header.twig' with {
    title: post.title,
} only %}