簡體   English   中英

Symfony2循環參考

[英]Symfony2 Circular reference

可能我的模板循環有問題。

services:
    twig_menu:
        class: Cms\PageBundle\Twig\Menu
        arguments: ['@doctrine.orm.entity_manager', "@templating"]

代碼php:

namespace Cms\PageBundle\Twig;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Templating\EngineInterface;
class Menu {
    protected $em, $templating;
    public function __construct(EntityManager $em, EngineInterface $templating){
        $this->em = $em;
        $this->templating=$templating;
    }
    public function show($typ){
        $menu=$this->em->getRepository("CmsAdminBundle:Menu")->findBy(array('type_id'=>$typ));
        return $this->templating->render("menu.html.twig", array('links'=>$menu));
    }
}

模板:

<ul>
    {% for link in links %}
        <li><a href="{{ link.href }}">{{ link.name }}</a></li>
    {% endfor %}
</ul>

當我在第一次刷新時清除緩存它沒關系,接下來我得到這個錯誤:

檢測到服務“模板”的循環引用,路徑:“模板 - >樹枝 - > twig_menu”。

templating需要twigtwig需要twig_menutwig_menu需要templating 因此你的循環參考問題。 這可能是因為你處於開發模式,因為有了分析器,Twig有更多的依賴關系。

Fabien Potencier本人已經在GitHub上回答了這個問題 :“只需注入服務容器並從中獲取Twig”。 這是一個快速而骯臟的解決方案,但它應該沒有任何嚴重的懲罰。

但是因為注入服務容器是一種代碼味道,你可能想要避免它。 更深(更正確)的解決方案是重構,使twig不依賴於twig_menu ,但不知道你的整個項目,很難說你怎么能做到這一點。

注入樹枝服務,而不是模板服務。 @twig是服務名稱。

您可以使用setter方法提供它,而不是在twig_menu服務的構造函數中注入模板服務。 例如:

public function setTemplating(TwigEngine $templating)
{
    $this->templating = $templating;
}

然后在你的控制器中使用:

$this->get('twig_menu')->setTemplating($this->get('templating'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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