Mixing templates and data directly inside application code is rarely a good idea. That is exactly the kind of problem MVC patterns were created to solve. Because of its history, WordPress does not use a full MVC architecture by default. Still, that does not mean we cannot improve template structure inside a WordPress project.
Twig is one of the most widely used template systems in PHP. Even without adopting a complete MVC framework, we can still use Twig in WordPress templates and make rendering cleaner and more maintainable.
Install Twig with Composer
The simplest way is to install Twig directly inside the WordPress theme directory through Composer.
composer install twig/twig
Configure the Twig template directory and cache directory
After installation, load Composer’s autoload file, then configure the template directory and the cache directory. Once those are set up, Twig is ready to use.
require_once( dirname( __FILE__ ) . '/vendor/autoload.php' );
$loader = new Twig_Loader_Filesystem(dirname( __FILE__ ) . '/tmp');
$twig = new Twig_Environment($loader, array(
'cache' => dirname( __FILE__ ) . '/tmp',
));
Pass data to the template and render it
In the following example, the template file being loaded is tmp/index.html. After that, data is passed into the template as an array and rendered directly. To keep the example simple, the data here is just a string, but in a real project it could be posts, users, settings, or any other application data.
$template = $twig->loadTemplate('index.html');
echo $template->render([ 'data' => '测试模板加载' ]);
Replacing the entire standard WordPress theme system with Twig may be a fairly aggressive move, and there can be some rough edges in practice. But if you are building an application on top of WordPress, or rendering just one part of a WordPress theme or plugin, Twig can be a very convenient way to separate presentation from logic.
