Sf2.0, standard blog for example.
Code of routing.yml:
DevBlogBundle_post_show:
pattern: /posts/{id}
defaults: { _controller: "DevBlogBundle:Post:show" }
requirements:
_method: GET
id: \d+
Standard way i generate url for my post by using:
path('DevBlogBundle_post_show',{'id':post.id})
I use this constrution in all my temlates/layouts, which include posts list. An if i want to change my route for post_show (say… add Slug parameter /posts/{id}.{slug}), i will need to change all my temlates. Instead, i want to generate route by my Post model, something like:
public function getUrl(){
return $this->generator->generate('DevBlogBundle_post_show',array (...params...));}
Question: How can i get This Generator to my Post model, what i have to “use …” and how to generate route?
In my templates i want to place:
<a href="{{ post.getUrl() }}" ...>...</a>
Thanks in advance.
Excited by this question and the thoughts in my previous comment i’ve hacked together a quick proof of concept to achieve what you where asking for. I’ve implemented a twig function that can be passed an entity and a route name. The function does the following setps to generate the url:
However this implies that the routes parameters are named exactly as the properties in the entities, which IMHO is a good practice anyway. The code needs to be places into a twig extension that has the service container reference injected into the container property.
In twig you can then call the function with
{{post|entity_url('DevBlogBundle_post_show')}}.But I’m asking myself why there is no implementation yet in symfony… or why i have not found it yet.