Home > OS >  How to pass an element value into jinja using set
How to pass an element value into jinja using set

Time:08-22

so, I have this code:

button.on("click",()=>{
    "{% set sb = document.getElementById('inputval').value %}" 
window.location.href = "{{url_for('register',input=sb)}}" 
}) 

but when I run it, it showed to me this error: 'document' not defined

I tried this syntax too:

window.location.href = "{{url_for('register',input=" document.getElementById('inputval').value ")}}" 

but it showed to me the statement, not the value. I want to transfer an input value to a url, so I can deal with it

CodePudding user response:

Jinja is a template engine for Python and the

{% set sb = document.getElementById('inputval').value %}

code runs on your server (the same is true for your {{url_for('register',input=" document.getElementById('inputval').value ")}}).

document is an object you can use in Javascript once the template has been generated, sent out to the browser and the browser is rendering it or rendered it.

You will need to retrieve your URL via AJAX based on document.getElementById('inputval').value, that is, a click event happens in your browser (so the page was already sent out and your browser is evaluating your code and is unaware of anything Pythonic or Jinja-related).

During this click event you have some textual value, based on which your server can construct a URL. This means that you need to implement an API function on your server-side that receives a textual request parameter and builds a URL which is retrieved and consequently you need to send an AJAX request to your server before you redirect.

Alternatively you could implement a Javascript function that reliably returns the correct URL based on a textual input, in which case you do not even need to send a request to your server before redirecting. Instead, you call your function to retrieve this URL and then redirect to the resulting URL.

  • Related