Reputation: 4083
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 }} ?
Upvotes: 5
Views: 17705
Reputation: 4083
This worked for me.
In config.yml:
twig:
globals:
base_url: "http://www.example.com/"
In twig template:
{{ base_url }}
Upvotes: 3
Reputation: 2456
Add following setting in 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');
Upvotes: 4
Reputation: 2806
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:
base_url:
pattern: /
After that, you must set the router.request_context parameters as mentioned in the Symfony cookbook.
Now that everything's setup, you can simply use the same url functions in Twig as you would do in your webpages:
{{ url('base_url') }}
Upvotes: 3