7

I have a pretty simple site working in Flask that's all powered from an sqlite db. Each page is stored as a row in the page table, which holds stuff like the path, title, content.

The structure is hierarchical where a page can have a parent. So while for example, 'about' may be a page, there could also be 'about/something' and 'about/cakes'. So I want to create a navigation bar with links to all links that have a parent of '/' (/ is the root page). In addition, I'd like it to also show the page that is open and all parents of that page.

So for example if we were at 'about/cakes/muffins', in addition to the links that always show, we'd also see the link to 'about/cakes', in some manner like so:

- About/
  - Cakes/
    - Muffins
    - Genoise
  - Pies/
- Stuff/
- Contact
- Legal
- Etc.[/]

with trailing slashes for those pages with children, and without for those that don't.

Code:

@app.route('/')
def index():
    page = query_db('select * from page where path = "/"', one=True)
    return render_template('page.html', page=page, bread=[''])

@app.route('/<path>')
def page(path=None):
    page = query_db('select * from page where path = "%s"' % path, one=True)
    bread = Bread(path)
    return render_template('page.html', page=page, crumbs=bread.links)

I already feel like I'm violating DRY for having two functions there. But doing navigation will violate it further, since I also want the navigation on things like error pages.

But I can't seem to find a particularly Flasky way to do this. Any ideas?

3
  • 2
    Sorry, I'm not entirely sure what you're asking here - how to do what exactly? The way you're building the SQL query in your 'page' view is not safe, and is open to an injection attack. Have a look at some of the answers here to see how to handle user input safely.
    – DazWorrall
    Mar 19, 2013 at 14:04
  • 1
    Yes it's all temporary code, I know about SQL injection. I'm asking how I can get dynamic tree navigation working in Flask. I've done this before in django using mppt, but I don't see a Flask equivalent anywhere. Mar 19, 2013 at 14:08
  • 1
    I have a similar question, but additionally need the navigation to have access to flask.session variables. See stackoverflow.com/questions/45948609/… Aug 29, 2017 at 21:33

2 Answers 2

9

The "flasky" and pythonic way will be to use class-based view and templates hierarchy

First of all read documentation on both, then you can refactor your code based on this approach:

class MainPage(MethodView):
    navigation=False
    context={}

    def prepare(self,*args,**kwargs):
        if self.navigation:
            self.context['navigation']={
                #building navigation
                #in your case based on request.args.get('page')
            }
        else:
            self.context['navigation']=None

    def dispatch_request(self, *args, **kwargs):
        self.context=dict() #should nullify context on request, since Views classes objects are shared between requests
        self.prepare(self,*args,**kwargs)
        return super(MainPage,self).dispatch_request(*args,**kwargs)

class PageWithNavigation(MainPage):
    navigation = True

class ContentPage(PageWithNavigation):
    def get(self):
        page={} #here you do your magic to get page data
        self.context['page']=page
        #self.context['bread']=bread
        #self.context['something_Else']=something_Else
        return render_template('page.html',**self.context)

Then you can do following: create separate pages, for main_page.html and page_with_navigation.html Then your every page "error.html, page.html, somethingelse.html" based on one of them. The key is to do this dynamically:

Will modify prepare method a bit:

def prepare(self):
        if self.navigation:
            self.context['navigation']={
                #building navigation
                #in your case based on request.args.get('page')
            }
        else:
            self.context['navigation']=None
        #added another if to point on changes, but you can combine with previous one
        if self.navigation:
            self.context['extends_with']="templates/page_with_navigation.html"
        else:
            self.context['extends_with']="templates/main_page.html"

And your templates: main_page.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    {% block navigation %}
    {% endblock %}
    {% block main_content %}
    {% endblock %}
</body>
</html>

page_with_navigation.html

{% extends "/templates/main_page.html" %}

{% block navigation %}
        here you build your navigation based on navigation context variable, which already passed in here
{% endblock %}

page.html or any other some_page.html. Keep it simple!
Pay attention to first line. Your view sets up which page should go in there and you can easily adjust it by setting navigation= of view-class.

{% extends extends_with %}

{% block main_content %}
        So this is your end-game page.
        Yo do not worry here about navigation, all this things must be set in view class and template should not worry about them
        But in case you need them they still available in navigation context variable
{% endblock %}
1
  • What does your context['navigation'] look like? It seems like that's the core of the question, not composing pages or passing the breadcrumb to templates. Mar 30 at 15:26
2

You can do it in one function by just having multiple decorators :)

@app.route('/', defaults={'path': '/'})
@app.route('/<path>')
def page(path):
    page = query_db('select * from page where path = "%s"' % path, one=True)
    if path == '/':
        bread = Bread(path)
        crumbs = bread.links
    else:
        bread = ['']
        crumbs = None
    return render_template('page.html', page=page, bread=bread, crumbs=crumbs)

Personally I would modify the bread function to also work for the path / though.

If it's simply about adding variables to your context, than I would recommend looking at the context processors: http://flask.pocoo.org/docs/templating/#context-processors

3
  • It's not the breadcrumbs I'm interested in, those work already. I'm after that rest of the navigation to work. Mar 19, 2013 at 14:07
  • @Knyght: did you see the part about the context processors? Those should be able to fix this nicely for you. Just write a little context processor to automatically generate a navigation menu based on the given path (or request) and it should work.
    – Wolph
    Mar 19, 2013 at 14:13
  • Also, woops, I changed the way bread() works a while ago and forgot to update the first function, which is what you get when you repeat yourself, derp. Thanks for the multiple decorators tip. And I'll look into context processors. Thanks. Mar 19, 2013 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.