Twig template cannot include php template

后端 未结 3 1477
鱼传尺愫
鱼传尺愫 2021-01-13 10:00

I encountered a problem, which for me is quite not clear and hard to understand. I have tried to make calendar widget, which is supposed to be display on every page on my si

3条回答
  •  深忆病人
    2021-01-13 10:14

    NOTE: snippets below are totally non-tested.

    http://twig.sensiolabs.org/doc/functions/date.html

    The function date seems to create \DateTime object.

    {% set now = date() %}
    {% set offset = date(now.format('Y/m/01')).format(w) %} {# weekday of 1st day #}
    {% set number = now.format('t') %} {# days in month #}
    {% set koniec = 7 - ((offset + number) % 7) %}
    {% set aktualny = now.format('n') %} {# today #}
    

    However, if you wants to include original php file (say 'calendar.php') in twig, you have to write extension to get it work.

    class CalendarExtension extends \Twig_Extension
    {
        private $pathToPhp; //store that where the php file is
    
        public function setPhpFile($pathToPhp)
        {
            $this->pathToPhp = $pathToPhp;
        }
    
        public function getFunctions()
        {
            return array(
                new \Twig_SimpleFunction('calendar', array($this, 'showCalendar'))
            );
        }
    
        public function showCalendar([put arguments here if you need])
        {
            ob_start();
            include ($this->pathToPhp);
            return ob_get_clean();
        }
    }
    

    To make above work, you should create "tagged" service in container.

    in app/config/config.yml
    
    services:
        calendar_twig_extension:
            class: __Namespace__\CalendarExtension
            calls:
                - [setPhpFile, [__path to your calendar.php__]]
            tags:
                - [name: twig.extension]
    

    words that double-underscored should be replaced:

    • _ _ Namespace _ _ : Namespace of CalendarExtension
    • _ _ path to your calendar.php _ _ : full path to your calendar.php. You can use parameters like %kernel.root_dir% and so on to manage your path project-relative.

    With these, you finally can simply write

    {{ calendar([arguments for CalendarExtension::showCalendar]) }}
    

提交回复
热议问题