Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom twig functions in laravel using TwigBridge

Tags:

php

laravel

twig

I'm using twig with laravel using TwigBridge. I'd like to register a custom function to use from within twig templates.

The documents states that extensions can be added via the extension-array, but this isn't clear to me.

What extension array is the documentation referring to?

like image 243
murze Avatar asked Dec 02 '22 23:12

murze


2 Answers

The process I followed was:

  1. Create my filters class at app/extensions/twig/TwigFilters.php:

    namespace App\Extensions\Twig;
    
    class TwigFilters extends \Twig_Extension {
        //... filters implementation
    }
    
  2. Add the filter folder to composer.json autoload > classmap

    "autoload": {
        "classmap": [
            ...
            "app/extensions/twig",
            ...
        ]
    },
    
  3. Update autoloader: php composer.phar dump-autoload

  4. Create the TwigBridge config at app/config/packages/rcrowe/twigbridge/config.php:

    php artisan config:publish rcrowe/twigbridge
    
  5. Edit the extensions key on the previously created config.php:

    'extensions' => array(
        ...
        'App\Extensions\Twig\TwigFilters',
        ...
    )
    
  6. All filters defined in that class are already available in the Twig views.

Additional Info:

  • Twig Extensions documentation
like image 126
ivanicus Avatar answered Dec 05 '22 14:12

ivanicus


What is referring is to this array in the config file. You should publish the config to your app/ using php artisan config:publish rcrowe/twigbridge and then edit that array. As you can see in the same config file you can also add alias.

You can create a class with your custom functions extending \TwigBridge\Extension and then add it to your config.

like image 31
ipalaus Avatar answered Dec 05 '22 12:12

ipalaus