Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Generating URLs from a template correctly in Symfony2/Twig

Tags:

php

twig

symfony

I'm working with Symfony2 and:

I have this in the routing.yml

_welcome:     resource: "@AcmeBundle/Controller/"     type:     annotation 

I this method within a controller:

/**  * @Route("/{page}")  */ public function staticAction($page) {     return $this->render('AcmeBundle:Static:'.$page.'.html.twig'); } 

To generate common pages:

/home /contact  /privacy 

But when I make the url on the menu:

<a href="{{ path('_welcome', {'page': 'home'}) }}">Home</a> <a href="{{ path('_welcome', {'page': 'contact'}) }}">Contact</a> <a href="{{ path('_welcome', {'page': 'privacy'}) }}">Privacy</a> 

And I Symfony generates these urls:

…./?page=home …./?page=contact …./?page=privacy 

And the right would be:

/home /contact /privacy 

What must I do?

like image 946
rpayanm Avatar asked Apr 07 '13 00:04

rpayanm


People also ask

How do I get the current URL in twig?

You can get the current URL in Twig/Silex 2 like this: global. request. attributes. get('_route') .

Is twig a template engine?

Twig is a modern template engine for PHPSecure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.

How do twig files work?

Twig works by taking all the hocus pocus out of template design. Templates are basically just text files that contain variables or expressions that are replaced by values as the template is evaluated. Tags are also an important part of a template file, as these control the logic of the template itself.


1 Answers

You've to add a route name in your controller route annotations as follow,

/**  * @Route("/{page}", name="static")  */ public function staticAction($page) {     // ...  } 

You could then call the twig path helper using that name,

<a href="{{ path('static', {'page': 'home'}) }}">Home</a> 
like image 191
Ahmed Siouani Avatar answered Oct 06 '22 00:10

Ahmed Siouani