Home > other >  Jinja2 and Javascript Reference Error when accessing HTML elements
Jinja2 and Javascript Reference Error when accessing HTML elements

Time:01-29

I am trying to create a form in Flask whereby when a user clicks on an object in a table a readonly form is populated with the value related to that object.

The problem I am having is when I pass that content value {{user.content}} to the Javascript that will update the form I am getting an error Uncaught ReferenceError: foo is not defined, where foo == user.content.

Not sure what is going on here besides my value being passed as a variable object and not a string. I have tried casting to a string like so:

onclick="displayResponse({{user.content|string}})"

But that does not seem to make any difference. Any idea how I can correct this?

The JS itself is correct, if I hardcode the value the form updates fine.

<div >
    <label for="exampleFormControlTextarea1">Response Data</label>
    <textarea  id="response-form-output" placeholder="root" rows="3" readonly></textarea>
  </div>


{% for user in users %}
<tr>
    <td>
        <button type="button"  onclick="displayResponse({{user.content}})">{{user.name}}</button>
    </td>
    <td>
        {{user.content}}
    </td>
    <script type="text/javascript">
        function displayResponse(data) {
            document.getElementById("response-form-output").value=data;
        }
    </script>
</tr>
{% endfor %}

CodePudding user response:

Jinja2 does not aware of the actual context of the variable, it just replaces the variable with its value. It's your job to make sure that the resulting source code has correct syntax. In your case the displayResponse JS function expect a string parameter, so we need to produce one:

<button type="button"  onclick="displayResponse('{{user.content}}')">{{user.name}}</button>

If user.content is e.g. "test string", then this becomes: displayResponse('test string'). Without the apostrophes, JS try to get the non-existing test and string variables. Make also sure that you replace every apostrophe in user.content with the respective HTML entity, otherwise it will produce a syntax error.

  •  Tags:  
  • Related