How to route multiple nav items in one folder using flask

Viewed 95

I'm developing a tourism website using flask. I have a destinations folder with names of cities. When the dropdown navigation item is clicked, these cities appear and upon click on a city, the page should be redirected to the relevant city. The navigation code is as follows;

<li><a href="#">Destinations</a>
  <ul class="nav-dropdown">
   <li><a href="destinations/london">London</a></li>
   <li><a href="destinations/paris">Paris</a></li>
   <li><a href="destinations/newyork">New York</a></li>
   <li><a href="destinations/moscow">Moscow</a></li>
   <li><a href="destinations/vegas">Las Vegas</a></li>
   <li><a href="destinations/pataya">Pataya</a></li>
  </ul>
</li>

The demo.py code is as follows;

from flask import Flask, render_template

@app.route('/destinations/{id}', methods = ['GET'])
def destinations(id):
    page = 'destinations/'+id+'.html'
    return render_template(page)

How to route this pages properly?

2 Answers

There's only a slight mistake in your code. You have to change the curly braces of id in /destinations/{id} toas /destinations/<id> and then the code will work perfect...

I'd have a context processor, which maintains a dictionary of the required links:

@app.context_processor
def processor():
  """ This function injects vars into every page """
  cities = {
            'paris':'Paris',
            'newyork': 'New York',
            'moscow':'Moscow',
            'vegas':'Las Vegas',
            'pataya':'Pataya'
            }
  
  return dict(CITIES=cities)

At some point you could build this dictionary from a database or other storage.

Then include in your template:

<li><a href="#">Destinations</a>
  <ul class="nav-dropdown">
   {% for city_id,city_name in CITIES.items() %}

     <li><a href="{{ url_for('destinations', id=city_id) }}">{{city_name}}</a></li>

   {% endfor %}
  </ul>
</li>

This url_for function, generates a URL like: /destinations/paris.

This method avoids having to manually write city names/ids into your template file.

Related