Search code examples
wordpresswoocommercetwigtimber

can i pass my php code to twig code of timber


I would like to know if I can convert any types of PHP code to twig, what I want to know is, for example, whether I can pass the code.

<?php
if (ICL_LANGUAGE_CODE == 'in'):?

to

{{ lang.en }}

Is there a way to add any PHP code and turn it into a twig and recognize it?

I use the Timber template for WordPress.


Solution

  • There is a good way to pass your functions (more correctly, register the function to Twig).

    Using Timber Hook: timber/twig

    There is a class in filter hook timber/twig could help us pass functions to Twig. It calls Timber\Twig_Function.

    new Timber\Twig_Function(
        'function_name_that_will_be_called_in_Twig',
        'function_name_in_php'
    );
    
    // OR
    new Timber\Twig_Function(
        'function_name_that_will_be_called_in_Twig',
        function( $input ) {
            // anonymous function is ok too.
        }
    );
    

    functions.php

    add_filter( 'timber/twig', 'add_to_twig' );
    
    function hello_in_php( $name = 'world' ) {
        $hello = 'Hello ';
        $hello .= $name;
    
        return $hello;
    }
    
    function add_to_twig( $twig ) {
        $func = new Timber\Twig_Function('hello', 'hello_in_php');
        $filter = new Timber\Twig_Function('introduce', function( $name ) {
            return "I'm ${name}!";
        });
    
        $twig->addFunction($func); //Registering a pre-defined function
        $twig->addFunction($filter); //Registering a filter function
    
        return $twig;
    }
    

    index.twig:

    <p id='a'>{{ hello() }}</p>
    <p id='b'>{{ hello('who?') }}</p>
    <p id='c'>{{ "Batman"|introduce }}</p>
    

    Result is:

    <p id='a'>Hello World</p>
    <p id='b'>Hello who?</p>
    <p id='c'>I'm Batman!</p>
    

    Source: https://timber.github.io/docs/guides/extending-timber/#adding-functionality-to-twig