Using Twitter Bootstrap radio buttons with Flask Using Twitter Bootstrap radio buttons with Flask flask flask

Using Twitter Bootstrap radio buttons with Flask


If you have big sets of similar controls — best way to use loops for them. Let's imagine we use list for storing all button names, and other list of buttons that are acive. This will give us some controller:

from flask import render_template@app.route('/form/')def hello(name=None):    return render_template('hello.html', buttons=['A', 'B', 'C'], active_btns=['A', 'C'])

So, in template we'll have something like:

<div id="radios1" class="btn-group view-opt-btn-group" data-toggle="buttons-radio">{% for button in buttons %}    {% if button in active_btns %}        <button type="button" class="btn active" name="choice1" value="{{ button }}">{{ button }}</button>    {% else %}        <button type="button" class="btn" name="choice1" value="{{ button }}">{{ button }}</button>    {% endif %}{% endfor %}</div>

Actually, expression inside for loop can be simplified, using Jinja's If expression, and should look like:

<button type="button" class="btn{{" active" if button in active_btns}}" name="choice1" value="{{ button }}">{{ button }}</button>

But I don't have Jinja2 now, and could be wrong in syntax.

If I didn't got your question right — please write some comment, I'll try to update my answer :)


As for setting the active box, I'm not sure what you mean, but the button tag attribute autofocus may be helpful. And it might be a good idea to just leave the fields blank initially.

You can pass the selected box to Flask without JavaScript using the following Flask code (your HTML currently is set up correctly to pass requests to Flask when the Submit button is pressed):

from flask import Flask, render_template, request@app.route("/", methods = ["GET", "POST"])def home():    if request.method == "POST":        button = request.form['choice1'] #this retrieves which radio button was pressed        if button == 'A': #if the button with attribute value = "A' is pressed            #what you want to do when button A is pressed        elif button == 'B':            #what you want to do when button B is pressed        elif button == 'C':            #what you want to do when button C is pressed        elif button == 'D':            #what you want to do when button D is pressed        elif button == 'E':            #what you want to do when button E is pressed    return render_template("home.html")