Answer a question

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.

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]);
}
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐