Hi all, I’m using Flask to build my site, currently I have a navbar setup with links to my other pages, here’s one:
<li _class_="nav-item"> <a _class_="nav-link" _href_="{{ _url_for_('pictures',_filename_='templates/pictures.html') }}">Pictures</a> </li>
Now it links fine and works as I want it to, however it also adds the filename after the URL: http://127.0.0.1:5000/pictures?filename=templates/pictures.html. Is there any way to remove the filename, so the address bar simply reads http://127.0.0.1:5000/pictures
Any help would be appreciated.
(I’m self-taught when it comes to HTML and CSS, so forgive any obvious mistakes. if you need any more code, just ask)
Thanks
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Enter your email to get $200 in credit for your first 60 days with DigitalOcean.
New accounts only. By submitting your email you agree to our Privacy Policy.
Heya,
To achieve this in Flask, you don’t typically pass the template name through the URL as you’re doing. Instead, you should separate the routing logic from the template rendering.
Here’s a simple refactoring of your situation:
In your Flask app, you’d define a route for ‘pictures’ that will render the desired template:
This sets up a route
/pictures
which will render thepictures.html
template when accessed.In your HTML (probably within a base template if you’re using one), your link to the pictures page would look like:
By doing this, the resulting link will be
http://127.0.0.1:5000/pictures
without any extra query parameters.render_template
function looks for templates in a folder namedtemplates
by default. So you typically don’t includetemplates/
in the template name.url_for
takes the name of the function (the view function in Flask terminology) as its argument, not the template filename. Henceurl_for('pictures')
corresponds to thepictures
function in your Flask app.templates
folder in the same directory as your Flask script, and that’s where you put yourpictures.html
file.