Is there a way to control the width of wtf.form_field input fields without affecting the label width?
Asked Answered
S

3

8

I am currently rendering several Flask fields (SelectFields, InputFields) using the following jinja2 template:

<div>{{ wtf.form_field(form.blockingProbability) }}</div>

This results in the following format:

Current rendering

I'd like to control the width of the dropdown list (narrower width would look more natural, methinks), but (unsurprisingly) when I try doing this by controlling the div width, the entire field, including the label is constrained and the label text wraps around.

Is there any way to control the width of the dropdown field (and other input fields), while keeping the width of the label intact (unwrapped)?

Scorpion answered 5/7, 2015 at 9:57 Comment(2)
Can you post the code of your form class?Onfre
Are you using flask-bootstrap?Onfre
S
12

This worked for me
jinja2 template:

<div style="width: 50%">
    {{ form1.language.label }}
</div>
<div style="width: 25%">
    {{ form1.language }}
</div>

enter image description here

This is the form1 class:

class myForm(Form):
   language = SelectField(u'Programming Language', choices=[('cpp', 'C++'), ('py', 'Python'), ('text', 'Plain Text')])
Stormy answered 5/7, 2015 at 11:15 Comment(2)
I was hoping to find a way to do this directly with wtf.form_field() rendering to maintain visual consistency with other fields that won't require width override, but I can live with this (just need to use the same method for all fields, even the ones at 100% width).Scorpion
Also works,{{ form1.language (style="width:25%;") }}Prizefight
O
2

This should work too and it also maintain the visual consistency with other fields' widths:

<div>{{ wtf.form_field(form.blockingProbability, horizontal_columns=('lg', 2, 4)) }}</div>

The last value - 4 - in horizontal_columns sets the width of the input field.

Onfre answered 5/7, 2015 at 15:46 Comment(1)
Thanks. At least for me, this only works for form_type="horizontal" (rather than "basic"), but this might come in useful at some later stage. <div>{{ wtf.form_field(form.blockingProbability, form_type="horizontal", horizontal_columns=('lg', 6, 3)) }}</div>Scorpion
H
0

When the Jinja2 code is rendered to HTML it will fill in a bunch of attributes on each form field. For your example, if you examine the page after it renders it should look something like:

<div>
    <label for='blockingProbability'>
        Blocking Probability
    </label>
    <input id='blockingProbability' name='blockingProbability' ... >
</div>

So you can control the fields and labels as a group or individually by adding some CSS into your Jinja2 template head:

<head>
    <style type="text/css">
        input {
            width: 20px;
        }
    </style>
</head>
Halothane answered 17/1, 2019 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.