![](/img/trans.png)
[英]Symfony 2 generate:bundle - with or without namespace /Bundle/
[英]Symfony 3 - menu without bundle
我有一個很大的靜態主菜單,只有3個項目需要從數據庫中加載。 這些項目有自己的子項,因此它們位於多維數組中,每個項目都需要有自己的select,因此3x select = 3x multi array。
我認為我不需要任何捆綁銷售商品,因為選擇此商品既快捷又容易。 (+這是具有非標准db結構的項目,因此實現捆綁可能會更困難)
但是我是Symfony的新手,所以我的問題是如何在一個地方從db加載菜單項,然后將其發送給視圖? 我不想在每個控制器/方法中加載此項目。
我已經嘗試過使樹枝擴展,但是在獲得此數組后,我需要對其進行迭代並在php類中構建html字符串...我認為這是一個非常糟糕的主意...
Twig Extension是前往此處的正確方法。 但是您不必在PHP中構建html字符串(這確實是錯誤的)。 您可以在擴展類中呈現Twig模板。
示例代碼:
<?php
namespace AppBundle\Twig;
class MenuExtension extends \Twig_Extension
{
public function __construct() //suitable dependecies here - probably Doctrine
{
//assign params to class properties
}
public function getName()
{
return 'menu_extension';
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('menuRenderer', [$this, 'menuRenderer'], [
'needs_environment' => true,
'is_safe' => ['html']
])
];
}
public function menuRenderer(\Twig_Environment $environment)
{
//do all the work to get data from DB
return $environment->render('AppBundle:Menu:main-menu.html.twig', array(
//pass data to template
));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.