jarednova/timber — pull request #281 by mgmartel (2014-07-03 10:43:23+00:00)
Title: Timber template hierarchy

Now that the query is added to the context by default (#277), the WordPress template files often just repeat the same melody.. get context and render a twig file with pretty much the same name as the php template.

So I quickly put together this PR (which is a proof-of-concept for discussion), which adds a template loader to the default WP template loading that loads twig templates according to the same logic as the WP template hierarchy if no php template is found.

It checks what the query is for, and checks if an appropriate twig template exists in any of the Timber locations, exactly as the WP Template hierarchy does. If a twig template is found, it is rendered using
the default context (`Timber::get_context()`).

For example, if the query is for a single post of the `portfolio` post type, the following files will be looked for:
* `child-theme/single-portfolio.php`
* `parent-theme/single-portfolio.php`
* `child-theme/single.php`
* `parent-theme/single.php`

..and then..

* `child-theme/views/single-portfolio.twig`
* `parent-theme/views/single-portfolio.twig`
* `child-theme/views/single.twig`
* `parent-theme/views/single.twig`

...and then...

* `child-theme/index.php` (NB!)
* `parent-theme/index.php`
* `child-theme/views/index.twig`
* `parent-theme/views/index.twig`

As a proof-of-concept, I have included a naked version of the starter theme in this PR, so you can see that the sites can actually run without template files :)

A few notes:
* Themes are required to have an `index.php`, so the code in the PR checks the `index.php` in a hacky way: if `{template}.twig` is not found, it renders the found `index.php` and sees if there is any output. If there is output, it will use `index.php`. If there's no output, it will continue looking for `index.twig`. (there is a filter to override this) We may have to think this through.
* I added a filter on the context as loaded by the template loader. That way, developers can choose to do away with php template files while still adding contextual context (ahem.) by filtering template loader context and adding stuff based on the global query vars (for example, author info on author archives).
* The code filters on the `get_index_template` function. If a timber template is found, it is rendered and the filter returns `false`. WP will then simply not include a template file... unless a plugin has filtered `template_include` to use its own templates (WooCommerce? BuddyPress?). This is something test and perhaps find solution for...

Let me know if you agree this is a valid strategy, then I'll work it out some more and write tests.