0

I am trying to use a javascript variable in a python dictionary in html, is this possible? Any help would be great.

e.g if I had a dictionary - current_data

var num_key = "4";

alert( {{ current_data[num_key] }} );

If I do the following it works perfectly, alert( {{ current_data["4"] }} );

But with the javascript variable, it won't work. Thanks again.

1 Answer 1

2

No, while you can use Jinja to create JavaScript embedded in <script> tags, you cannot use it the other way around. When Flask renders this page it's static. The page does not still have blocks of code inside {{ }} or {% %}, it holds the result of those operations. However, there are other options. You could put the contents of current_data into hidden input with the keys as the id attributes.

View

{% for key in current_data %}
    <input id="{{ key }}" type="hidden" value="{{ current_data[key] }}"/>
{% endfor %}

JavaScript

var num_key = "4";
alert(document.getElementById(num_key).value);

One extra piece of advice, it's not good practice to embed JavaScript into your html. You should have a separate .js file containing this and then include it in your html.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.