How to insert checkbox dynamically from Python/Flask code?

Asked

Viewed 300 times

3

I am trying to create a script in Flask and came across the following situation:

I have in my code a for that sweeps the subdirectories of a root directory:

for root, dirs, files in os.walk(destination):
    for name in dirs:
        ...

I need to put a checkbox list in my html layout with the names of the subdirectories found respectively

Example: my for found 4 sub-directories (dir1, dir2, dir3, dir4). Therefore, in my layout will have 4 checkbox (dir1, dir2, dir3, dir4).

Anyone can help?

2 answers

0

The easiest way is to do this directly on Jinja2

{% for d in dirs %}
    <input id="{{d}}" name="{{d}}" type="checkbox">
{% endfor %}

0

from flask import Flask
import os # os.walk()

app = Flask("checkboxes") # from flask

def checkboxes(directory):
    all_names = ""
    template = "{}: <input type=\"checkbox\" value=\"{}\"/><br>\n"

    for root, dirs, files in os.walk(directory):
        for name in dirs:
            all_names += template.format(name) # name vai para {0}.
    return all_names

@app.route("/")
def main():
    return checkboxes(".") # retorna all_names para a página.

app.run()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.