[英]symfony3.4 service container in template
我确实已经在MainBundle / MainFunctions /中定义了服务,并且可以在Controller中调用该服务。 如何现在在模板中的SYMFONY 3.4中获取服务容器? 阅读不再公开的文档。
#view/template.html.php
<?php $shop_id = $this->container->get('main_functions')->getSessionShopId(); ?>
我的config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
- { resource: "@FrontendMainBundle/Resources/config/services.yml
我的FrontendMainBundle / Resources / config / services.yml
services:
_defaults:
public: true
frontend_locale.locale_listener:
class: Frontend\MainBundle\EventListener\LocaleListener
arguments: ["%kernel.default_locale%"]
tags:
- { name: kernel.event_subscriber }
main_functions:
public: true
class: "%main_functions_class.class%"
arguments: ['@translator', '@doctrine.orm.entity_manager'....
我阅读了不再公开的文档。 但是我无法进入模板中的main_functions。 怎么样?
谢谢!!!
如果您的模板需要一些技巧,我建议您使用树枝扩展名: https : //symfony.com/doc/current/templating/twig_extension.html
您将可以调用{{yourFunction}}
这很简单。
MatMouth的答案是从树枝模板与服务进行交互的最佳方法。 您可以在模板中为需要访问的每种方法创建函数。 尝试将对象添加为细枝变量不是一个好习惯,除非它只是像使用Doctrine实体那样的基本吸气剂。
这是一些有关设置新功能并将其注册到容器服务中的重要文档:
https://symfony.com/doc/3.2/templating/twig_extension.html
您也可以注册过滤器而不是功能。 两者之间的区别是函数语法someFunction(someVar)
和过滤器someVar|someFilter
。 如果需要在函数或过滤器中添加其他参数,只需将参数添加到可调用对象中即可。
这是Twig的一些文档:
https://twig.symfony.com/doc/2.x/advanced.html
您可以做一些很酷的事情,例如使HTML安全,注入树枝环境等。
祝您好运,编码愉快!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.