Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript variable while accessing a Jinja template value [duplicate]

I am using python jinja2 to pass json into a HTML file. The json I pass is similar as below,

result = { "config":{ "firstTitle" : "Report" } }

In my HTML file I have a javascript function as follows which works as expected,

    function dispDetails()
    {
        //This works as expected
        //It print 'Report' in the console
        console.log('{{ config.firstTitle }}');
    }

But if my javascript function is modified as to include a javascript variable the code is throwing erros,

function dispDetails()
    {
        //Error thrown : jinja2.exceptions.TemplateSyntaxError: expected name or number
        titleStr = "firstTitle";
        console.log('\'{{ config.'+titleStr+' }}\'');
    }

I have tried various ways to get this working, not sure where I am going wrong and would need some guidance on the same.

like image 277
nidHi Avatar asked Aug 03 '26 03:08

nidHi


1 Answers

Jinja variables are ONLY set at render time and what you are trying to do is impossible.

This is pseudo code, but you could potentially declare a js variable with your jinja json and access that:

var config = {{ config | tojson }};
function dispDetails()
{
    titleStr = "firstTitle";
    console.log(config[titleStr]);
}
like image 185
dizzyf Avatar answered Aug 05 '26 15:08

dizzyf



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!