0

TL;DR --> can I pass JS var strings into {{ }} to retrieve Python vars from Flask app?

Instead of writing multiple iterations of a JS code block each with only slightly differently named Jinja variables (with similar conventions) like:

 //PTC Color Change
if ({{ptc_precip_probs[1]}} <= 25 && {{ptc_precip_probs[2]}} <= 25) {
    $("#ptc_block").css("background", "#21CE99"); //green
} else {
    $("#ptc_block").css("background", "#F45531"); //red
}

//COL Color Change
if ({{col_precip_probs[1]}} <= 25 && {{col_precip_probs[2]}} <= 25) {
    $("#col_block").css("background", "#21CE99"); //green
} else {
    $("#col_block").css("background", "#F45531"); //red
}enter code here

is it possible to do something like this:

var cities = ["nrg", "rrg", "gsm", "ptc", "col"];

for (var city in cities){
    var block = "."+cities[city]+"_block";
    var precipOne = String(cities[city])+"_precip_probs[1]";
    var precipTwo = String(cities[city])+"_precip_probs[2]";
    if ({{precipOne}} <= 25 && {{precipTwo}} <= 25) {
        $(String(block)).css("background", "#21CE99"); //green
    } else {
        $((block)).css("background", "#F45531"); //red
    }
}

When I attempt to do this exact operation, however I receive a Jinja2 error.

tmdangerous
  • 75
  • 1
  • 9

1 Answers1

1

No, because JS is client-side. From http://jinja.pocoo.org/docs/2.10/templates/#

A template contains variables and/or expressions, which get replaced with values when a template is rendered; and tags, which control the logic of the template. The template syntax is heavily inspired by Django and Python.

But if you want a variable from your flask app, you can pass it to the render_template function as demo'd in the question asked here Include html file in Jinja2 template

PGHE
  • 1,585
  • 11
  • 20