Search code examples
pythonflaskjinja2flask-loginflask-principal

How can I hide certain links in jinja2 template engine using Flask-Login and Permission class from Flask-Principal?


I am following the documentation and have already created my Permission instances so I can decorate my route functions, however, I have no idea how to hide links in the template. I saw an answer on here that used Roles but is there a way to use Permissions from Flask-Principal instead?

Hiding inaccessible links in Jinja2 templates The question asker's answer here sounds really good but would throw out my Permissions, also I don't really understand what he's doing, only that he doesn't have to re initialize the permissions/roles on the jinja2 template side.

My goal is to understand each flask extension's use as I learn. That's why I want to know if there's a way to do this without having to use Flask-Security or throwing out the Permissions I've already defined with Flask-Principal.


Solution

  • I use Flask-Nav with Flask-Bootstrap for creating navigation bar and I think you should follow its structure in your code as well. There are 2 basic steps:

    1. Define a (multi dimensional) list of navigation links in your app code, where you can use all your Permissions during the process. Pass this filtered list to your template.
    2. In your template loop over the list and generate a nice HTML code from it.

    IMHO it is the right way to create a role- or permission-dependant navigation bar, because it separates the HTML-generating code from the "app" code.