Twig - Get URL for canonical tag
Asked Answered
H

2

16

I'm looking to create a dynamic rel="canonical" tag in my application which pulls in the current URL but want to ensure any query parameters are removed. E.g http://www.example.com/test/?page=2 should have the canonical as http://www.example.com/test/, therefore {{ app.request.uri }} doesn't work as this pulls in ?page=2 as well.

Does anyone know how to pull in the absolute path of a page without the query parameters?

Hypothec answered 3/11, 2013 at 22:6 Comment(2)
I don't think it's possible (maybe I'm wrong), but you could write Twig extension that splits app.request.uri by ? char...Ace
I've just remembered that there is app.request.baseUrl. Have you tried that?Ace
D
24

This will work,

{{ url(app.request.attributes.get('_route'), app.request.attributes.get('_route_params')) }}
Dias answered 4/11, 2013 at 9:55 Comment(5)
+1 Haven't tried it but this seems to be really neat solution :)Ace
Aren't query strings provided in the route params?Lecce
@SteveBuzonas, nope it's only generate url base on current route name and it's params. If u have additional query strings u need to add it by yourselfDias
In your 404 page if you extend the template this code is used in, make sure to put this inside an if block or 404 page will become a 500 page because route doesn't exist.Osbourne
it's ugly as sin, but it still gets the job done in Symfony 4.4. Thanks!Birdman
A
7

I just tried to dump baseUrl and can confirm that it does not work.

However, this works:

{{ app.request.getSchemeAndHttpHost ~ app.request.baseUrl ~ app.request.pathInfo }}

I know, it's not pretty but it does the job :)

Ace answered 3/11, 2013 at 23:57 Comment(2)
This is what i am looking for, above solution not including parameters to generated url.Reformed
this should be the accepted answer, cause the other one will result in 500 errors for every single error page like 403, 404, and so on!Pilferage

© 2022 - 2024 — McMap. All rights reserved.