Display a variable template in jinja2

  flask, jinja2, python

Problem:
I have an app built with flask and python and a MySQL Database.
In the settings page the user can set different modules for the home page to be his/her first module / second module and so on.

main.py

@app.route("/home")
def home():
    try:
        f = open("session.txt")
        f.close()
    except IOError:
        return redirect("/", code=302)
    f = open("session.txt")
    user=f.readline()
    f.close()
    mydb = mysql.connector.connect(
        host="localhost",
        user="private",
        password="passgfdsg453#",
        database="settings"
    )
    mycursor = mydb.cursor()
    sql = "SELECT * FROM " + user + " WHERE position ='1'"
    mycursor.execute(sql)
    moduleOne = mycursor.fetchall()
    print(moduleOne)
    for x in moduleOne:
        print(x)
        moduleOneHTML = x[1]+".html"
        print(moduleOneHTML)

This fetches the first module, in my case "ModTime.html". Here I am trying to insert it into the include tag. But it won’t work. Here you can see my home.html

{% extends "base.html" %}

{% block content %}
<main class="flex-shrink-0">
  <div class="container">
    <br>
    <h1 class="mt-5">{{ l.1 }} {{ user }}</h1>
    <br>
    <div class="row mb-4">
      {% include {{ ModuleOneHTML }} %}
    </div>
</main>

{% endblock %}

if idea in anyone:

   print("You are awesome!")

EDIT:

{% for a in ModuleOneHTML %}
{% include a + ".jinja" %}
{% endfor %}

This seems to work but does not output anything. It does not give an error anymore but displays nothing where the Template should be included

Source: Python Questions

LEAVE A COMMENT