简体   繁体   中英

Is it possible to use a user-defined JS variable string to impute into a Flask Variable?

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.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM