In my Flask app I am using a form with a SelectField to select a color.
When rendering this field in my html, using jinja2, I would like to have the text for each color be styled in the corresponding color.
Currently when the SelectField items are rendered on the html form they only have the attribute of "value".
I was attempting to solve the problem by adding an attribute for "style" so that I can set the css text color by directly referencing the value field (which contains a string for the hex representation of the desired color).
Is there a better way to do this?
Here is what I am getting currently:
Which is rendered using the code:
form = MyForm()
class MyForm(FlaskForm):
... other form fields ...
color = SelectField('Base Color:', choices=[('#0390fc','Blue'),('#41fc03','Green'),('#ca03fc','Purple')], validators=[DataRequired()])
... other form fields ...
<!-- Color form group -->
<div class="form-group">
{{ form.color.label(class="form-control-label") }}
{% if form.color.errors %}
{{ form.color(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.color.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.color(class="form-control form-control-lg") }}
{% endif %}
</div>
And which returns the html:
<!-- Color form group -->
<div class="form-group">
<label class="form-control-label" for="color">Base Color:</label>
<select class="form-control form-control-lg" id="color" name="color" required>
<option value="#0390fc">Blue</option>
<option value="#41fc03">Green</option>
<option value="#ca03fc">Purple</option>
</select>
</div>
I would like my SelectField options to look more like this:
Which I have been able to generate so far by modifying my jinja2 code as:
<!-- Color form group -->
<div class="form-group">
{{ form.color.label(class="form-control-label") }}
{% if form.color.errors %}
{{ form.color(class="form-control form-control-lg is-invalid") }}
<div class="invalid-feedback">
{% for error in form.color.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.color(class="form-control form-control-lg") }}
{% for subchoice in form.color %}
{{ subchoice(**{'style': 'color:' + subchoice.object_data + ';'}) }}
{% endfor %}
{% endif %}
</div>
This returns html with the desired option list, however, the list is outside of the portion of the SelectField, which makes it useless:
<!-- Color form group -->
<div class="form-group">
<label class="form-control-label" for="color">Base Color:</label>
<select class="form-control form-control-lg" id="color" name="color" required>
<option value="#0390fc">Blue</option>
<option value="#41fc03">Green</option>
<option value="#ca03fc">Purple</option>
</select>
<option style="color:#0390fc;" value="#0390fc">Blue</option>
<option style="color:#41fc03;" value="#41fc03">Green</option>
<option style="color:#ca03fc;" value="#ca03fc">Purple</option>
</div>