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

ⅰ亾dé卋堺 提交于 2020-12-11 10:00:24

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/43758751/using-javascript-variable-while-accessing-a-jinja-template-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!