As Twig 2.0 is approaching fast now, it's time to focus on how to boost adoption of this new major version. Twig 2.0 is not a revolution, but rather like Symfony 3.0, a version where we've done a lot of cleanup, dropped support for old PHP versions, fixed wrong behaviors, and simplified things whenever possible. Everyone should be able to upgrade very easily to Twig 2.0.

Also, the good news is that most of the time, it's possible to make your code work for both major versions (that's important for shared code like bundles). Of course, deprecated features in Twig 1.x have been removed in Twig 2.0, so you might need to upgrade your code to make it compatible with both major versions. How to make it easy? Like for Symfony, I've now added deprecation notices throughout the code to give Twig users an easy way to upgrade their code (this is available in the upcoming Twig 1.21 version).

If you are using Symfony, just upgrade to Twig 1.21 (not yet released), and the `symfony/phpunit-bridge` component or the Symfony Web Profiler will do the rest. Run your test suite and you will get deprecation notices from Twig.

If you want to upgrade the templating part, Twig 1.21 comes with the Twig_Util_DeprecationCollector class that makes the process easy. For more information, read the dedicated Twig recipe.

If you have some node visitors, there is now a base class that makes it easy to make the code compatible for both versions of Twig. Here is how to make Drupal 8 compatible with Twig 2.0:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
diff --git a/core/lib/Drupal/Core/Template/TwigNodeVisitor.php b/core/lib/Drupal/Core/Template/TwigNodeVisitor.php
index ac1e676..860cc56 100644
--- a/core/lib/Drupal/Core/Template/TwigNodeVisitor.php
+++ b/core/lib/Drupal/Core/Template/TwigNodeVisitor.php
@@ -16,19 +16,19 @@
  *
  * @see twig_render
  */
-class TwigNodeVisitor implements \Twig_NodeVisitorInterface {
+class TwigNodeVisitor extends \Twig_BaseNodeVisitor {

   /**
    * {@inheritdoc}
    */
-  public function enterNode(\Twig_NodeInterface $node, \Twig_Environment $env) {
+  protected function doEnterNode(\Twig_Node $node, \Twig_Environment $env) {
     return $node;
   }

   /**
    * {@inheritdoc}
    */
-  public function leaveNode(\Twig_NodeInterface $node, \Twig_Environment $env) {
+  protected function doLeaveNode(\Twig_Node $node, \Twig_Environment $env) {
     // We use this to inject a call to render_var -> TwigExtension->renderVar()
     // before anything is printed.
     if ($node instanceof \Twig_Node_Print) {

What about Symfony itself? Well, when this pull request is finished and merged, Symfony 2.3 and up will be compatible with both Twig 1.x and 2.x. That's a first step. If you are the maintainer of some public bundles, do the same and let us know!

Published in #Community #Symfony #Twig