3

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();
3
  • JavaScript looks cleaner. Easier to handle logic there, too. Commented May 18, 2018 at 4:30
  • You are asking the wrong question. The Jinja template is not supported to handle the logic, therefore the if statement should be done at the Flask route function and pass in the color attribute as part of the template context to the Jinja template so that it can be rendered, e.g. <div id="NRG" style="background: {{ color }}"> Commented May 18, 2018 at 4:46
  • None is good. Use css and add sorresponding class to the NRG element Commented May 18, 2018 at 6:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.