TWIG with wordpress part2

TWIG with wordpress part2

Using TWIG plug in we made in part1 of this article

It’s highly advised to read part1 first to understand what’s going on.

When our TWIG engine autoloader is ready, and our plugin is activated from wp-admin side, we can go to wordpress themes folder and make new theme folder. Inside our theme folder, let’s make starter file: ‘index.php’ slightly modified to fit our needs:

<?php
wp-content/themes/Our theme folder/index.php
/**
 * The main template file.
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package Our theme
 * @subpackage Our theme
 */
 
$loader = new Twig_Loader_Filesystem(dirname(__FILE__));
$twig = new Twig_Environment($loader, array(
            'cache' => false
        ));
$template = $twig->loadTemplate('index.html.twig');
 
$template->display(array('variable1'=>$variable1,'variable2'=>$variable2 ...));

After we made that, we should make starter file for out twig theme: index.html.twig and all the other necessary files for our theme with twig templating possibilities.

But, there is one more problem with wordpress: How can we reach easy way wordpress environment functions defined from our TWIG template?

We should pass that variables somehow to TWIG so they can be used.

After some brainstorming, I made to this solution:
let’s make a some kind of proxy class in our twig engine plugin folder so we could pass instance of that class to our twig engine and make all necessary calls to wordpress functions from inside that class. Is that many work to do? Must we define all the wordpress functions inside our class to reach them?
No. Let’s add this to our custom file that we autoloaded in part1, so our file looks like this:

<?php
 
<?php
/*
…. /wp-content/plugins/wp_twig_engine/Wp_TwigEngine.php
  Author: Darko Goleš
  Author URI: https://inchoo.net/author/darko.goles/
*/
*
 
class Wp_TwigEngine_Autoloader {
 
    static public function register() {
        ini_set('unserialize_callback_func', 'spl_autoload_call');
        spl_autoload_register(array(new self, 'autoload'));
    }
 
    static public function autoload($class) {
        if (0 !== strpos($class, 'Wp_TwigEngine')) {
            return;
        }
 
        if (file_exists($file = dirname(__FILE__) . '/../' . str_replace(array('_', "\0"), array('/', ''), $class) . '.php')) {
            echo($file);
            exit;
            require $file;
        }
    }
 
}
 
class OurTwigProxy {
 
    public function __call($function, $arguments) {
 
        if (!function_exists($function)) {
            trigger_error('call to unexisting function ' . $function, E_USER_ERROR);
            return NULL;
        }
        return call_user_func_array($function, $arguments);
    }
}

You see, I used php __call function to make this class somekind proxy for our wp functions.

Let’s see our index.php inside our theme folder now:

$site = new OurTwigProxy();
$loader = new Twig_Loader_Filesystem(dirname(__FILE__));
$twig = new Twig_Environment($loader, array(
            'cache' => false
        ));
$template = $twig->loadTemplate('index.html.twig');
 
$template->display(array('site' => $site));

you see, now we made instance of our autoloaded ‘proxy’ class an passed it into template.
From inside template we can now call any WP functions that we need:

#{file: index.html.twig}#

{% if site.is_category %}
...
Hello from here
...
{% endif %}

Those two articles about twig was just idea, and I didn’t finish this project yet. I will try to finish this code and also implement ‘yaml’ config file possibilities to be used for wordpress theming, but that will be content of next part. Thanks for now, and I would like you to leave some comments what you thing about this idea.

Cheers

You made it all the way down here so you must have enjoyed this post! You may also like:

TWIG with WordPress part1 Darko Goles
Darko Goles, | 1

TWIG with WordPress part1

Parsing Amazon affiliate links in WordPress Darko Goles
Darko Goles, | 1

Parsing Amazon affiliate links in WordPress

Symfony 2 paginator – improved version Darko Goles
Darko Goles, | 0

Symfony 2 paginator – improved version

9 comments

  1. Hi,

    We develop a plugin for WordPress which uses Twig under the hood. It allows you to create template right in the WordPress admin and inject it anywhere in your site with shortcodes. It is called Inject and you can have a look at it in action right here : http://inject.netcod.es
    You can create basically anything like : posts list, author box, social sharing widget, newsletter opt-in widget, a special button to stick anywhere… or more complex stuff !

    Hope this can help…

    Best regards,

    Quentin

  2. Hi,
    very interesting! I used Twig outside Symfony time ago… amazing!
    so when I see the Twig integration inside WP I became very happy.
    I’m interesting to new application of Twig inside WP have you make some else?
    for example implementation of yaml config?

    thanks a lot!
    Gianluigi

    1. Unfortunately, I stopped working on this, since I switched to Magento last year exclusively 🙂

  3. Hi,

    thanks for this tutorial! Interesting ideas 🙂 But I have another problem, maybe you can help me.

    I only want to use the {% render %} command of twig in my WordPress templates. It is even not necessary to use twig. I am looking for a way to get the response of a specific symfony2 controller inside wordpress.

    I have a controller action that renders a twig template which contains a html list filled up with items from doctrine. And my problem is that I don’t know how to use this action inside wordpress.

    Does anybody have an idea?

    Kind regards
    Simon

  4. Great articles. I’m suprised that using Twig in wordpress hasn’t attracted more attention (and also this post). I have a Django background and smiled when Sensio Labs introduced Twig. Theming in wordpress is painful with all the html intermingled with php.

    Nice use of __call and call_user_func_array, I’ve used them in exactly the same way before.

    Have you got any further since this post?

  5. @Mikael, thanks for your comment. I didn’t have time to finish it yet, but when I succeed, it will be published here. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.