1
votes

I try to call a static helper method inside Twig (Timber). {{ function('Theme\Helpers::get_template_name') }}

Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'ThemeHelpers' not found in /var/www/html/wp-content/plugins/timber-library/lib/Twig.php on line 268.

Does anyone know how to call a method of a different class inside Twig?

3

3 Answers

1
votes

As far as I know you can't call PHP classes directly from your twig template. What you can do is setting up a Twig filter which communicates with your class and returns the needed value.

You would have this in your php controller file that is responsible to load your twig template:

<?php

function twg_get_template_name() {

    # edit this according to the implementation of your class:
    return Helpers::get_template_name();
}

function add_to_twig($twig) {
    /* this is where you can add your own fuctions to twig */
    $twig->addExtension(new Twig_Extension_StringLoader());
    $twig->addFilter('twg_get_template_name', new Twig_Filter_Function('twg_get_template_name'));
    return $twig;
}

add_filter('get_twig', 'add_to_twig');

In your Twig template you would call the filter like this:

{{ ''|twg_get_template_name }}

Because it's a filter function it expects a value "to filter", so pass at least an empty string.

If I were in that situation I probably would determine the name of the template in your controller and send the value to your Twig template directly instead of calling the php class via a filter-function.

0
votes

Thanks for your answer.

I tried your approach - it works. But using a filter feels a little hacky, especially when no value is passed. Why not create a timber function the same way as a filter? Bridging own functions from plain php into twig is not great, but I also don't see another solution to this.

After playing around a little, I came up with a different approach. I now fixed my need by customizing the Timber Object and adding a template property to the post variable.

Looks something like this:

class OnepagePost extends TimberPost {

    var $_template;

    // Add template property to Twig Object
    public function template() {

        return Helpers::get_template_name( $this->custom['_wp_page_template'] );

    }

}

Then inside the .php file where the Twig View gets called, I called the custom object like this:

$context['posts'] = new Timber\PostQuery( $args, 'OnepagePost' );
Timber::render('onepager.twig', $context);

Inside the Twig Template I'm able to get my custom property very easy (in my way the template):

{% for post in posts %}

    {% include ["section/section-#{post.template}.twig"] %}

{% endfor %}
0
votes

You can call static functions from a Twig file in Timber using the array notation, where first item is the name of the class and the second item the name of the static method you want to call:

{{ function( [ 'Theme\Helpers', 'get_template_name' ] ) }}