[英]service method as twig global variable
在我的symfony2應用程序中,我有一個getPorfolioUser方法,它返回一個特定的用戶變量。
我很期待能打電話
{%if portfolio_user%}
在樹枝上。 我不明白如何將其設置為全局變量,因為我在印象中只能設置固定元素或服務而不是服務方法。
我是否有義務為此編寫擴展或幫助? 這樣做的簡單方法是什么?
謝謝!
您可以將自定義服務定義為twig globals variable
,如下所示:
# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
globals:
myGlobaService: "@acme.demo_portfolio_service" #The id of your service
{% if myGlobaService.portfolio_user() %}
希望這有幫助
一種方法是使用CONTROLLER事件監聽器。 我喜歡使用CONTROLLER而不是REQUEST,因為它確保所有常規請求監聽器已經完成了它們的工作。
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProjectEventListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array
(
KernelEvents::CONTROLLER => array(
array('onControllerProject'),
),
);
}
private $twig;
public function __construct($twig)
{
$this->twig = $twig;
}
public function onControllerProject(FilterControllerEvent $event)
{
// Generate your data
$project = ...;
// Twig global
$this->twig->addGlobal('project',$project);
}
# services.yml
cerad_project__project_event_listener:
class: ...\ProjectEventListener
tags:
- { name: kernel.event_subscriber }
arguments:
- '@twig'
聽眾在此處記錄: http : //symfony.com/doc/current/cookbook/service_container/event_listener.html
另一種方法是完全避免樹枝全球化,只是進行枝條延伸調用。 http://symfony.com/doc/current/cookbook/templating/twig_extension.html
無論哪種方式都很好。
當你看到這里: http : //symfony.com/doc/current/reference/twig_reference.html#app
你可以讀到這個:
app變量隨處可用,可以訪問許多常用的對象和值。 它是GlobalVariables的一個實例。
GlobalVariables
是Symfony\\Bundle\\FrameworkBundle\\Templating\\GlobalVariables
我從來沒有這樣做,但我認為一種方法是覆蓋這個課程,以滿足你的特殊需求。
我也遇到了一些困難,最后通過以下方式解決了這個問題:
設置你的包(例如:MyVendor / MyBundle)
$ app/console generate:bundle
在此類文件中,創建該函數
public function getExample(){ return "it works!!!"; }
在app / config / services.yml中創建一個新服務,如下所示:
myvendor.mybundle.myservice class: MyVendor\\MyBundle\\DependencyInjection\\MyService
在根據樹枝配置部分的應用程序/配置/ config.yml
twig: globals: mystuff: '@myvendor.mybundle.myservice'
然后在您的twig模板中,您可以像這樣引用變量:
{{ mystuff.example }}
免責聲明
這就是我如何讓它工作....
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.