From fa08e76f093141e5db3f2dd5ea61b76f79da6558 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sat, 7 Jan 2012 09:53:33 +0100 Subject: [PATCH] added a recipe for stateful node visitors --- doc/recipes.rst | 23 +++++++++++++++++++++++ 1 files changed, 23 insertions(+), 0 deletions(-) diff --git a/doc/recipes.rst b/doc/recipes.rst index 122c777..0335335 100644 --- a/doc/recipes.rst +++ b/doc/recipes.rst @@ -275,4 +275,27 @@ rewrites the cache:: } } +Reusing a stateful Node Visitor +------------------------------- + +When attaching a visitor to a ``Twig_Environment`` instance, Twig uses it to +visit *all* templates it compiles. If you need to keep some state information +around, you probably want to reset it when visiting a new template. + +This can be easily achieved with the following code:: + + protected $someTemplateState = array(); + + public function enterNode(Twig_NodeInterface $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_Module) { + // reset the state as we are entering a new template + $this->someTemplateState = array(); + } + + // ... + + return $node; + } + .. _callback: http://www.php.net/manual/en/function.is-callable.php -- 1.7.2.5