From: Fabien Potencier Date: Sat, 7 Jan 2012 08:53:33 +0000 (+0100) Subject: added a recipe for stateful node visitors X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=fa08e76f093141e5db3f2dd5ea61b76f79da6558;p=web%2Fkonrad%2Ftwig.git added a recipe for stateful node visitors --- 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