Shan
Shan

Reputation: 1138

How to load Jinja2 template with values after form submission

I have a form in a Jinja2 template. This is what I'm trying to do with it:

What is the best way to do this ? For example say I have a <select> input in my form that looks like this:

  <select id="shift_selected" name="shift_selected">
  {% for shift in Shifts %}
    <option value="{{ shift }}" {{ 'selected' if shift == selected_shift }}>{{ shift }}</option>
  {% endfor %}
  </select>

Now to re render the page after the form has been submitted,

args['selected_shift'] = self.request.get("selectedShift")

template.render(args)

The handler essentially receives some data in form values and sends the same data back as a template variable value. Is there a better way to do this. If done for a long form this method is quite tedious.

Upvotes: 0

Views: 1821

Answers (1)

郑福真
郑福真

Reputation: 314

Actually, you can even pass request object as a param to Jinja template. Or write a function to copy all the GET or POST parameters in request to Jinja template parameters.

args['request'] = self.request
template.render(args)

<select id="shift_selected" name="shift_selected">
{% for shift in request.get('selectedShift') %}
    <option value="{{ shift }}" {{ 'selected' if shift == selected_shift }}>{{ shift }}</option>
{% endfor %}
</select>

Upvotes: 1

Related Questions