How to Debug Timber Theme? (Use var_dump)

One convenient way to figure out Timber's stuff by yourself is to dump the variable and methods. We will show you how in this article.

Timber is a plugin to allow separation between PHP and HTML files. Click here for introduction.

Timber is not a commonly-used plugin. Aside from the official documentation and few Stack Overflows threads, it can be tough to find the information you need.

One convenient way to figure out Timber by yourself is to dump the variable and methods. We will show you how in this article.

1. Add Dump Filter

We will add 2 new filters: dump for listing all variables and methods for listing all methods.

NOTE: Please read our tutorial on adding new filters to know where to put the snippet below.

class MyTimber extends TimberSite {
  ...
  
  function add_to_twig( $twig ) {
    // only if set to Debug mode
    if( defined('WP_DEBUG') && WP_DEBUG === true ) {
      $twig->addFilter( new Twig_SimpleFilter( 'dump', [$this, 'filter_dump'] ) );
      $twig->addFilter( new Twig_SimpleFilter( 'methods', [$this, 'filter_methods'] ) );
    }
    return $twig;
  }

  function filter_dump( $var ) {
    var_dump( $var );
  }

  function filter_methods( $object ) {
    var_dump( get_class_methods( $object ) );
  }
}

2. Enable DEBUG Mode

Open your wp-config.php file and near the bottom of it, change WP_DEBUG to true.

...
define('WP_DEBUG', true);
...

3. Try it Out

Let’s say you want to display Author info. You are not sure how, so you check what’s inside post variable:

{{ post | dump }}
Dumping Post’s variable in Timber

After taking a quick look, there doesn’t seem to be any data about the author’s name. The closest thing is post_author which only shows Author ID.

But don’t stop there, try checking the methods:

{{ post | methods }}
Dumping Post’s methods in Timber

Nice! We found author method, let’s try to see what’s inside that:

{{ post.author | dump }}
Dumping Post Author’s variable in Timber

There we go! We found the display name, description, and all other data about the author.

Wait for a second, there’s no avatar data! Check the methods and you will see that it’s available as {{ post.avatar }}.


Conclusion

This tip is especially useful if you try to integrate a 3rd party plugin like WooCommerce with Timber.

Always Google what you need first. If you can’t find the information, proceed to dissect the variable with this method. Common WordPress stuff like the example above can actually be found in the official docs.

As always, let me know in the comment below if you have any question 🙂

Default image
Henner Setyono
A web developer who mainly build custom theme for WordPress since 2013. Young enough to never had to deal with using Table as layout.
Leave a Reply to BasiaCancel Reply

One comment

  1. Great post! Helped me a lot with debugging. Thanks 🙂