简体   繁体   中英

Render Symfony 5 service as twig global

I'm using a service as twig global variable. In the service constructor I set a default value of the property $title . It works initially.... Twig render the property value using the command {{ service.getTitle() }} in a template file. But after update the service property by the controllers constructor and rendering the view, the value is not updated at screen. The goal is set a twig global variable by the controllers to render in all views. How to do it?

  • twig.yaml

     twig: globals: pageMap: "@Base.PageMap"
  • services.yaml

     services: Base.PageMap: class: App\Bundle\Base\Services\PageMap public: true
  • controller

     public function __construct(PageMap $pageMap) { $pageMap->setTitle('Registration listing'); }
  • twig template:

     <div class="title">{{ pageMap.getTitle() }}</div>

Twig globals are setup at init time and compiled/cached for the duration of an execution.

If you want to update and be able to call things dynamically, you should create a RuntimeExtension (see documentation here: https://symfony.com/doc/current/templating/twig_extension.html#creating-lazy-loaded-twig-extensions )

Calling it from your template will be a little more expensive (but more correct !)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM