phpwordpresstwigtimber

WordPress + Timber + Twig i18n extension


I'm trying to implement localization to a site I'm currently building. My goal is to use the i18n Extension for Twig since that's my template engine of choice.

However, when I'm adding the extension the site just crashes, screen gets white, and returning a 500 error code. Log says 408 timeout. In the same function where I'm adding the extension I also added another extension which works great. I have successfully installed the extensions via Composer. (https://twig-extensions.readthedocs.io/en/latest/i18n.html)

What am I doing wrong?

Here's my function.php

<?php
/**
* Timber starter-theme
* https://github.com/timber/starter-theme
*
* @package  WordPress
* @subpackage  Timber
* @since   Timber 0.1
*/

Timber::$dirname = array( 'templates');
/** Start Timber! */

class StarterSite extends Timber\Site {
    /** Add timber support. */
    public function __construct() {
    add_theme_support( 'post-formats' );
    add_theme_support( 'post-thumbnails' );
    add_filter( 'timber_context', array( $this, 'add_to_context' ) );
    add_filter( 'get_twig', array( $this, 'add_to_twig' ) );
    add_filter('show_admin_bar', '__return_false');
    define( 'WP_DEBUG', true );
    parent::__construct();
}

function add_to_context( $context ) {
    $context['site'] = $this;
    return $context;
}

public function add_to_twig( $twig ) {
    $twig->addExtension( new Twig_Extension_StringLoader() );
    $twig->addExtension( new Twig_Extensions_Extension_I18n() ); // This line breaks the site
    return $twig;
}
}

new StarterSite();

Solution

  • When working with WordPress and Timber, you don’t need to use Twig’s i18n extension, as stated in the Internationalization Guide in Timber’s documentation:

    Twig has its own i18n extension that gives you {% trans %} tags to define translatable blocks, but there’s no need to use it, because with Timber, you have all you need.

    This means that in your Twig templates, you can use all the functions that you’d normally use with normal WordPress templates. Here’s an example for a button.

    <button>{{ __('Submit', 'my-text-domain') }}</button>
    

    You can set up your theme for internationalization like you would in a normal WordPress theme. Follow the Internationalization section in the Theme Handbook.

    Set up your style.css with a text domain and a domain path:

    /**
     * Theme Name: My Theme
     * Author: Theme Author
     * Text Domain: my-text-domain
     * Domain Path: /languages
     */
    

    Then, WordPress will look for a my-text-domain.pot file in the /languages folder of your theme. You can generate that POT file with Poedit Pro. Poedit Pro will find the translations in your Twig file.