![](/img/trans.png)
[英]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.