Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Jinja2 Statements vs. JavaScript Use Case

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();
like image 408
tmdangerous Avatar asked Jun 21 '26 19:06

tmdangerous


1 Answers

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.

like image 61
Dave W. Smith Avatar answered Jun 23 '26 10:06

Dave W. Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!