0

In my Jinja template for Flask application I have this snippet:

{% elif mydata.accepted==True %}
    {% set accept_off = 'Yes' %}
    {{accept_off}}
{% else %}

It sets value and renders in the html. Works fine.
Javascript snippet:

<script>
        $(document).ready(function () {
            console.log( "ready!" );
            alert('{{ accept_off}}'); // comes empty, though rendered in template
            alert('{{ datafromserver}})'; // works fine
            var item = ('{{set accept_off = yes}}');
            alert(item); // works as well

...

This snippet alerts empty "accept_off" variable though in template it renders fine. And second alert with data from server passed during rendering it works fine as well.

So how does it work that I cannot set variable in Jinja template and then use it in javadcript?

Tomas Am
  • 433
  • 4
  • 13
  • Probably not the bug you are looking for, but the last apostrophe should be inside the parentheses `alert('{{ datafromserver}})';` should be `alert('{{ datafromserver}}');` – Ambassador Kosh May 13 '21 at 20:37
  • Thanks for note, yes it's not the main issue here. Do you knowi f setting variable in jijna template should be accesable in js? – Tomas Am May 14 '21 at 05:20
  • This post might help you https://stackoverflow.com/questions/21626048/unable-to-pass-jinja2-variables-into-javascript-snippet It is possible though I couldn't say whether it is possible for your scenario. I have only ever needed to do this once when creating modals for every post on a page e.g. `var modal = document.getElementById("postModal{{ post.id }}");`. This worked fine, though it was in the html page within ` – Ambassador Kosh May 14 '21 at 11:26
  • To me it looks a scope issue. You can use a namespace to solve it. More here: https://jinja.palletsprojects.com/en/2.10.x/templates/#assignments https://jinja.palletsprojects.com/en/2.10.x/templates/#namespace – voscausa May 14 '21 at 12:03

0 Answers0