How to generate a url from symfony2 route name in a twig template?

I want to avoid hard-coding relative URLs in my twig templates in a Symfony2 project.

I have defined some route names in my controllers, for example:

@Route("/", name="homepage")

Is there a Twig or Symfony2 function that could help me generate links properly? Something like:

<a href='{{ magic_fct("homepage") }}'>Home</a>

would return:

<a href='/'>Home</a>

Upvotes: 4

Views: 5135

Answers (2)

Federkun
Federkun

Reputation: 36924

Yes, of course you can. Take a look in Linking to Pages documentation.

<a href="{{ path('homepage') }}">Home</a>

Upvotes: 6

Jasmin Mistry
Jasmin Mistry

Reputation: 1476

Use following:

<a href='{{ path('homepage') }}'>Home page</a>

Upvotes: 8

Related Questions