[英]In symfony 2 how to access twig templating base url parameter in php?
[英]how to access base url in twig from symfony 2 console?
我正在將我在Kohana的網站逐漸移植到Symfony 2。 現在我在Symfony2中編寫后端命令,例如cron發送電子郵件通知。
如何在樹枝中訪問基本URL。 我可以進行一些配置,以便從控制台和http請求訪問twig中的URL是相同的嗎?
我已經參考了這個,
http://symfony.com/doc/current/cookbook/console/sending_emails.html
http://symfony.com/doc/current/cookbook/templating/global_variables.html
在這里,給出了如何配置它,但沒有提到如何訪問它,我假設我必須使用{{router.request_context.host}}。
但我的問題是,控制台和HTTP之間沒有任何方法可以保持一致嗎?
例如{{url}}?
在parameters.yml中添加以下設置,
router.request_context.scheme: http
router.request_context.host: domain.com
base_url: '%router.request_context.scheme%://%router.request_context.host%/'
和控制台命令控制器內部,你可以訪問,如,
$host = $this->getContainer()->get('router')->getContext()->getHost();
$scheme = $this->getContainer()->get('router')->getContext()->getScheme();
$baseURL = $this->getContainer()->getParameter('base_url');
首先,您必須通過將以下行添加到/app/config/routing.yml來設置路由中的URL(您將其稱為base_url):
base_url:
pattern: /
之后,您必須設置Symfony cookbook中提到的router.request_context參數。
現在一切都設置好了,您可以像在網頁中一樣在Twig中使用相同的url功能:
{{ url('base_url') }}
這對我有用。
在config.yml中:
twig:
globals:
base_url: "http://www.example.com/"
在樹枝模板中:
{{ base_url }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.