5

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 }} ?

3 Answers 3

4

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');             
Sign up to request clarification or add additional context in comments.

1 Comment

Hemant, The problem was how to access it in Twig template, not how to access in Controller. Anyways, this is Vishal Melmatti's profile, I have already fixed and committed the same in git 3-4 days before. :)
3

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') }}

5 Comments

As I have only backend commands in symfony 2 right now and dont have front end (which is in kohana now), can I use url() without argument to get base url ?
I updated my answer to add your "base_url" as a route. You call it base url, I call it the homepage! :-)
I dont have home page in symfony2, I have only symfony console commands. My website is in kohana.
You can create a route without actually having a controller/action linked to it. Just add the base_url route as provided in my example, it'll work.
Thats great, will try it.
3

This worked for me.

In config.yml:

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

In twig template:

{{ base_url }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.