简体   繁体   English

如何从symfony 2控制台访问twig中的基本URL?

[英]how to access base url in twig from symfony 2 console?

I am porting my website which is in Kohana to Symfony 2 gradually. 我正在将我在Kohana的网站逐渐移植到Symfony 2。 Right now I am writing backend command in Symfony2, eg cron to send email notifications. 现在我在Symfony2中编写后端命令,例如cron发送电子邮件通知。

How can I access base url in twig. 如何在树枝中访问基本URL。 Can I do some configuration so that accessing urls in twig from console and from http request to be same ? 我可以进行一些配置,以便从控制台和http请求访问twig中的URL是相同的吗?

I have already reffered to this, 我已经参考了这个,

http://symfony.com/doc/current/cookbook/console/sending_emails.html http://symfony.com/doc/current/cookbook/console/sending_emails.html

http://symfony.com/doc/current/cookbook/templating/global_variables.html http://symfony.com/doc/current/cookbook/templating/global_variables.html

here, it is given how to configure it, but it is not mentioned how to access it, I assume I have to use {{ router.request_context.host }}. 在这里,给出了如何配置它,但没有提到如何访问它,我假设我必须使用{{router.request_context.host}}。

But my question is, isn't there any way to be consistent between console and HTTP ? 但我的问题是,控制台和HTTP之间没有任何方法可以保持一致吗?

eg {{ url }} ? 例如{{url}}?

Add following setting in parameters.yml, 在parameters.yml中添加以下设置,

router.request_context.scheme: http
router.request_context.host: domain.com
base_url: '%router.request_context.scheme%://%router.request_context.host%/'

and inside console command controller you can access like, 和控制台命令控制器内部,你可以访问,如,

$host =  $this->getContainer()->get('router')->getContext()->getHost();
$scheme =  $this->getContainer()->get('router')->getContext()->getScheme();
$baseURL = $this->getContainer()->getParameter('base_url');             

First, you must set the url (you're calling it base_url) in a route by adding the following lines to /app/config/routing.yml: 首先,您必须通过将以下行添加到/app/config/routing.yml来设置路由中的URL(您将其称为base_url):

base_url:
    pattern:  /

After that, you must set the router.request_context parameters as mentioned in the Symfony cookbook. 之后,您必须设置Symfony cookbook中提到的router.request_context参数。

Now that everything's setup, you can simply use the same url functions in Twig as you would do in your webpages: 现在一切都设置好了,您可以像在网页中一样在Twig中使用相同的url功能:

{{ url('base_url') }}

This worked for me. 这对我有用。

In config.yml: 在config.yml中:

twig:
   globals:
       base_url: "http://www.example.com/"

In twig template: 在树枝模板中:

{{ base_url }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM