4

I am porting my website which is in Kohana to Symfony 2 gradually. Right now I am writing backend command in Symfony2, e.g. cron to send email notifications.

How can I access base url in twig. Can I do some configuration so that accessing urls in twig from console and from http request to be same ?

I have already reffered to this,

http://symfony.com/doc/current/cookbook/console/sending_emails.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 }}.

But my question is, isn't there any way to be consistent between console and HTTP ?

e.g. {{ url }} ?

4

3 回答 3

4

在 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');             
于 2013-08-02T08:37:03.683 回答
3

首先,您必须通过将以下行添加到 /app/config/routing.yml 来设置路由中的 url(您将其称为 base_url):

base_url:
    pattern:  /

之后,您必须按照 Symfony 手册中的说明设置 router.request_context 参数。

现在一切都已设置好,您可以在 Twig 中简单地使用与网页中相同的 url 函数:

{{ url('base_url') }}
于 2013-07-26T09:18:47.017 回答
3

这对我有用。

在 config.yml 中:

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

在树枝模板中:

{{ base_url }}
于 2013-08-06T08:09:36.607 回答