Med SAM
Med SAM

Reputation: 21

generate list in html in flask python dynamically without specifying each field in ul or tr

I am bit new in python and flask, i ve been trough lot of tutorial and web forums, couldn't find way to generate dynamically.

here's an example , html code :

<tr>
                <td scope='row'>{{ data["courseID"] }}</td>
                <td>{{ data["title"] }}</td>
                <td>{{ data["description"] }}</td>
                <td>{{ data["credits"] }}</td>
                <td>{{ data["term"] }}</td>
                <td>
                    <form action="{{url_for('enrollment')}}" method="POST">
                        <input type="hidden" name="courseID" value="{{data['courseID']}}">
                        <input type="hidden" name="title" value="{{data['title']}}">
                        <input type="hidden" name="term" value="{{data['term']}}">
                    <button>Enroll</button>
                </form>
                </td>
            </tr>
            {% endfor %}
            
            </tbody>
        </table>
    </div>
{% endblock %}

app py code is :

class Course(mongo.Document):
    courseID = mongo.StringField(max_length=10, unique=True)
    title = mongo.StringField(max_length=100)
    description = mongo.StringField(max_length=255)
    credits = mongo.IntField()
    term = mongo.StringField(max_length=25)
@app.route("/courses/")
@app.route("/courses/<term>")
def courses(term = None):
    if term is None:
        term = "Spring 2019"
    classes = Course.objects.order_by("-courseID")
    return render_template("courses.html", courseData=classes, courses = True, term=term )

what am looking for tutorial or way how to list all labels in one line and list all data in one line too in html code. reason for that, is in future am looking to display whole table that i generate from a query, and if each time i have to code that as class and in html (specially if columns are more that 10) will be time consuming. wasnt able to find proper example to learn from it.

Upvotes: 0

Views: 1201

Answers (1)

A.B
A.B

Reputation: 20445

One simple option can be to return classes as list of dict (records) , for example

return render_template("courses.html", courseData=classes.to_dict("records"), courses = True, term=term )

Then looping through the keys of the dict as

    {% for dict_item in courseData %}
<tr>
            {% for key, val in dict_item.items() %}
              <td>
                <td>{{ row[key] }}</td>
              </td>
            {% endfor %} }
</tr>
    {% endfor %}
      

You can do same thing for html form elements

Upvotes: 1

Related Questions