Using a custom function in twig

后端 未结 4 1888
失恋的感觉
失恋的感觉 2021-02-02 10:21

In my template I want to output the server timezone.

My template has something like

{{ getservertimezone }}

Then in the services.yml co

4条回答
  •  囚心锁ツ
    2021-02-02 10:29

    Symfony ^2.6 - twig ^1.38

    See example below


    AppExtension.php

    namespace Your/NameSpace;
    
    class AppExtension extends \Twig_Extension {
    
        public function getFilters() 
        {
            return array(
                new \Twig_SimpleFilter('cdn_asset_filter', array($this, 'cdn_asset_filter')),
            );
        }
    
        public function getFunctions()
        {
            return array(
                new \Twig\TwigFunction('cdn_asset_function', array($this, 'cdn_asset_function')),
            );
        }
    
    
        public function cdn_asset_filter($path) 
        {
            return "https://cdn.example.com/$path";
        }
    
    
        public function cdn_asset_function($path) 
        {
            return "https://cdn.example.com/$path";
        }
    }
    

    view.html.twig

    // Filter
    
    
    
    // result : 
    
    
    // Function
    
    
    
    // result : 
    

    app/config/services.yml

    services:
        my_global_filters_and_functions:
            class: Your/NameSpace/AppExtension
            tags:
                - { name: twig.extension }
    

    This is how i used custom functions in Twig in one my old projects, i don't know if it's a best practice, but it worked for me.


    Resources : Twig Documentation - Extending Twig

提交回复
热议问题