0

I am getting the following result set from my database,

    {
  "workbases": [
    {
      "workbase": "WB 1"
    }, 
    {
      "workbase": "WB 2"
    }, 
    {
      "workbase": "WB 3"
    }, 
    {
      "workbase": "WB 4"
    }, 
    {
      "workbase": "WB 5"
    }, 
    {
      "workbase": "WB 6"
    }, 
    {
      "workbase": "WB 7"
    }, 
    {
      "workbase": "WB 8"
    }, 
    {
      "workbase": "WB 9"
    }, 
    {
      "workbase": "WB 10"
    }, 
    {
      "workbase": "WB 11"
    }, 
    {
      "workbase": "WB 12"
    }, 
    {
      "workbase": "WB 13"
    }, 
    {
      "workbase": "WB 14"
    }, 
    {
      "workbase": "WB 15"
    }, 
    {
      "workbase": "WB 16"
    }
  ]
}

These results come from this code,

staff = tables.staff_list

sel = select([staff.c.workbase]).distinct(staff.c.workbase).select_from(staff).where(staff.c.workbase != "")

workbases = FlaskApp.db_connect().execute(sel).fetchall()
workbases = [utils.rowdict(a) for a in workbases]

workbases = jsonify(workbases=workbases)

return render_template('leave_request.html', hours_left=100, workbases=workbases)

How do I go about looking through the workbases data in my template, I have tried,

{% for w in workbases %}
    <option value="">{{ w.workbase }}</option>
{% endfor %}

and also

{% for w in workbases.workbases %}
    <option value="">{{ w.workbase }}</option>
{% endfor %}

but niether of them render any option within my select inputs (the code is nested within select tags

Udders
  • 6,914
  • 24
  • 102
  • 194
  • 2
    Why did you `jsonify` your data structure? *The `jsonify()` function in flask returns `flask.Response()` object*. -- http://stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonify#13172658 – OneCricketeer Nov 28 '16 at 11:46

2 Answers2

1

If you remove the line workbases = jsonify(workbases=workbases) from your python file. As cricket007 states, jsonify is a flask.Response() object used to send JSON data from Flask to something like an XHR call or an API call. It's an HTTP Response and will include content headers, etc.

Once you remove this the second Jinja2 method you described should work.

{% for w in workbases.workbases %}
    <option value="">{{ w.workbase }}</option>
{% endfor %}

This would produce the same results as:

{% for w in workbases['workbases'] %}
    <option value="">{{ w['workbase'] }}</option>
{% endfor %}

Because Jinja2 is not Python. See the documentation for more detail:

http://jinja.pocoo.org/docs/dev/templates/#variables

abigperson
  • 5,252
  • 3
  • 22
  • 25
0

Have you tried

{% for w in workbases['workbases'] %}
    <option value="">{{ w['workbase'] }}</option>
{% endfor %}
ArunDhaJ
  • 621
  • 6
  • 18
  • In jinja2 `workbases['workbases']` and `workbases.workbases` is essentially the same thing http://jinja.pocoo.org/docs/dev/templates/#variables – abigperson Nov 28 '16 at 14:36