I am creating my first small web app using the Flask framework and I am not sure which approach is best practice to change the properties of elements (ID='#NRG') on my page based upon data defined in the Python code on the backend:
Flask / Jinja2 Approach:
{% if nrg_precip_probs[0] <=25 and nrg_precip_probs[1] <= 25 and nrg_precip_probs[2] <=25 %}
<script>$("#NRG").css("background", "#21CE99");</script>
{% else %}
<script>$("#NRG").css("background", "#F45531");</script>
{% endif %}
or a JavaScript Approach:
function change_it() {
if ({{nrg_precip_probs[0]}} <= 25) {
$("#NRG").css("background", "#21CE99");
} else {
$("#NRG").css("background", "#F45531");
}
}
change_it();
If the page is generate once and won't be refreshing itself doing to data fetched from an AJAX request, one clean option is to do the calculation server-side, passing the boolean result to the template. Then, the template could do something like
<div id="#NRG" style="background: {% if low_precip_prob %}#21CE99{% else %}#F45531{% endif %}"> ...
Another approach, if you think you might be using more than one color in the future, is to calculate a class name server-side. This simplifies the template to
<div id="#NRG" class="{{ precip_class }}"> ...
but adds the requirement off having matching class names in your style sheet.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.