Search code examples
pythonhtmlflaskjinja2

How to make a checkbox checked in Jinja2


I am learning flask programming and cannot figure out how to make a radio input checked, here is the html template I am using:

<form method = "POST" action="/proxy_settings">
    <input type="radio" name="proxy_mode" value = '0'>Auto
    <br>
    <input type="radio" name="proxy_mode" value = '1'>Manual
    <br>
    <br>
    <section>
        <table border="1">
            <tr>
                <td>Description</td>
                <td>delay</td>
                <td>select</td>
            </tr>
            {% for node_name, node_delay in node_list.items() %}
            <tr>
                <td>{{node_name}}</td>
                <td>{{node_delay}}</td>
                <td><input type="radio" name="proxy_node"></td>
            </tr>
            {% endfor %}
        </table>
    </section>
    <br>
    <section>
        <button type="submit">CONFIRM</button>
    </section>
</form>

I am rendering this template in flask like this:

return render_template("base.html", node_number = ret["node_number"], proxy_mode = ret1["proxy_mode"], proxy_node = ret2["proxy_node"], node_list=ret3) 

My question is:

  1. How to make proxy_mode radio input checked according to the value of variable proxy_mode?
  2. How to make proxy_node radio input checked according to the value of variable proxy_node? For example, if proxy_node equals to 2, then the radio input in row 2 of the table will be checked.
  3. How to assign a value attribute dynamically to the radio input proxy_node?

I have tried the following method for question 1 but it doesn't work.

<input type="radio" name="proxy_mode" value = '0' {% if proxy_mode == 0 %} checked=true {% endif %}>Auto
<br>
<input type="radio" name="proxy_mode" value = '1' {% if proxy_mode == 1 %} checked=true {% endif %}>Manual

Thanks in advance!


Solution

  • This should be the easiest way.

    <input type="radio" name="proxy_mode" value="0" {{ "checked" if proxy_mode == 0 }}>Auto
    <br>
    <input type="radio" name="proxy_mode" value="1" {{ "checked" if proxy_mode == 1 }}>Manual