簡體   English   中英

模板中的symfony3.4服務容器

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM