-
Notifications
You must be signed in to change notification settings - Fork 3
Adding data context to a template
Each Twig template can access a global context. This context is added when the initial Twig template is rendered.
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.
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);
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);
The global context can be seen in Grrr\Theme\Setup
. You can add data there, which will make it available to all templates.
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 %}