Search code examples
javascriptpythonpython-3.xtornado

Can I call a JavaScript function from a tornado template if check?


I have a websocket based chatroom that performs translations based on the users desired language in the room. On the python side I populate both the spoken language and the translated language. I pass these values to a templated html page where I want to make a javascript call in the templated if check which will help me to decide which value to populate in the message window. Is this possible to do? I keep getting an error stating my return result is invalid. I have shared what I currently have in my template. The function getUser() is a javascript function and message is the param passed from python to the template.

<div class="message" id="m{{ message["id"] }}">
  {% if message["user"] == getUser() %}
    {% module linkify(message["translation"]) %}
  {% else %}
    {% module linkify(message["transcription"]) %}
  {% end %}
</div>

Solution

  • {% if message["user"] == getUser() %}
    

    You say that getUser() is a JS function. In that case, it won't work. This is because the templates are compiled at the server but the JS runs on the browser. Hence, getUser() function will not run.