added a debug tag
authorfabien <fabien@93ef8e89-cb99-4229-a87c-7fa0fa45744b>
Thu, 22 Oct 2009 01:56:15 +0000 (01:56 +0000)
committerfabien <fabien@93ef8e89-cb99-4229-a87c-7fa0fa45744b>
Thu, 22 Oct 2009 01:56:15 +0000 (01:56 +0000)
git-svn-id: http://svn.twig-project.org/trunk@90 93ef8e89-cb99-4229-a87c-7fa0fa45744b

doc/02-Twig-for-Template-Designers.markdown
lib/Twig/Extension/Core.php
lib/Twig/Node/Debug.php [new file with mode: 0644]
lib/Twig/TokenParser/Debug.php [new file with mode: 0644]

index 08da161..876d8eb 100644 (file)
@@ -582,6 +582,24 @@ to use them, they still need to be imported:
 
     <p>{{ forms.textarea('comment') }}</p>
 
+### Debug
+
+Whenever a template does not work as expected, the debug tag can be used to
+output the content of the current context:
+
+    [twig]
+    {% debug %}
+
+You can also output a specific variable or an expression:
+
+    [twig]
+    {% debug items %}
+
+    {% debug post.body %}
+
+Note that this tag only works when the `debug` option of the environment is
+set to `true`.
+
 Expressions
 -----------
 
index eab044e..b0b625a 100644 (file)
@@ -40,6 +40,7 @@ class Twig_Extension_Core extends Twig_Extension
       new Twig_TokenParser_Macro(),
       new Twig_TokenParser_Import(),
       new Twig_TokenParser_Set(),
+      new Twig_TokenParser_Debug(),
     );
   }
 
diff --git a/lib/Twig/Node/Debug.php b/lib/Twig/Node/Debug.php
new file mode 100644 (file)
index 0000000..c8d7b31
--- /dev/null
@@ -0,0 +1,39 @@
+<?php
+
+class Twig_Node_Debug extends Twig_Node
+{
+  protected $expr;
+
+  public function __construct(Twig_Node_Expression $expr = null, $lineno, $tag = null)
+  {
+    parent::__construct($lineno, $tag);
+
+    $this->expr = $expr;
+  }
+
+  public function compile($compiler)
+  {
+    $compiler->addDebugInfo($this);
+
+    $compiler
+      ->write("if (\$this->env->isDebug())\n", "{\n")
+      ->indent()
+      ->write('var_export(')
+    ;
+
+    if (null === $this->expr)
+    {
+      $compiler->raw('$context');
+    }
+    else
+    {
+      $compiler->subcompile($this->expr);
+    }
+
+    $compiler
+      ->raw(");\n")
+      ->outdent()
+      ->write("}\n")
+    ;
+  }
+}
diff --git a/lib/Twig/TokenParser/Debug.php b/lib/Twig/TokenParser/Debug.php
new file mode 100644 (file)
index 0000000..879db6c
--- /dev/null
@@ -0,0 +1,23 @@
+<?php
+
+class Twig_TokenParser_Debug extends Twig_TokenParser
+{
+  public function parse(Twig_Token $token)
+  {
+    $lineno = $token->getLine();
+
+    $expr = null;
+    if (!$this->parser->getStream()->test(Twig_Token::BLOCK_END_TYPE))
+    {
+      $expr = $this->parser->getExpressionParser()->parseExpression();
+    }
+    $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
+
+    return new Twig_Node_Debug($expr, $lineno, $this->getTag());
+  }
+
+  public function getTag()
+  {
+    return 'debug';
+  }
+}