Search code examples
wordpresstwigtwig-extension

Render with timber (twig) directly from string


I am trying to combine my wordpress project with Timber. To do it, I need to render twig templates through timber with wordpress global wp_query.

So far I found out solution for twig, and it works:

$twig = new \Twig_Environment(new \Twig_Loader_String());
return $rendered = $twig->render(
  "<title>{{ site.name }}</title>",
  array('site' => $site)
);

However, I have no idea how to do it using Timber. Only way I know is from .twig file. I was looking for solution, but found nothing. I need to pass many wordpress variables in order to use them in templates and Timber would do it automatically.


Solution

  • Looking through the source, it looks like there's a render_string() method. It should work mostly same as a regular render().

    $context = Timber::get_context();
    $context['foo'] = 'Bar!';
    $context['post'] = new TimberPost();
    Timber::render_string('{{ post.id }} - {{ foo }}', $context);