How to set javascript value to jinja variable - javascript

I know we can set Jinja variable to js variable like this.
var x = {{ 'value' }}
but I am trying to do the reverse. i.e I am trying to set javascript value to jinja variable. I tried the following but nothing worked.
{{value}} = x
{% set value = x %}
{% set value %} x {% endset %}
x is javascript variable.
is there any way to achieve this.

This is not possible, and reflects a deep problem in your understanding of the web application architecture. jinja2 is a templating engine for Python, running on your server. JavaScript you are talking about is running in your browser.
When a server receives a request, it processes a jinja2 template to obtain the response it will send to the client. You cannot "set Jinja variable to js variable", you can render the page in such a way that eventually a JavaScript variable would be assigned a value that was in a Jinja2 variable. I.e. you start with var x = {{ value }} in jinja2 template; jinja2 transforms it into var x = 42 during its rendering; then the rendered result gets sent to the client, which executes it as JavaScript, assigning a value 42 to x. The fact that there is a temporal sequence here (Python -> jinja2 -> rendered page source -> JavaScript) means you can't do what you want to do: The jinja2 variable and the JavaScript variable don't exist at the same time, nor in the same place, and assigning a JavaScript value to a jinja2 variable is impossible.
In order to send the value 42 to Python (and possibly later to jinja2), you would need to make a request that would send that value from client to server: a form submission, or an AJAX request.
You might get a better response if you would describe exactly what you want to do that you think requires you to "set javascript value to jinja variable".

This is an old thread and the answer might still be "it cannot be done" but I would like to point out a mistake in both the answers above. The Question is "How to set javascript value to jinja variable". What He is asking is if you have JavaScript running on your front end page that needs a certain value to work and that value is given by the backend script and passed in via Jinja2 can you make that work? (AJAX perhaps).. Both "Answers" above while detailed and informative don't address this question. They both seem to address the opposite question, "Can you set a jinja2 variable from a javascript" which I agree does not make sense.
I'm looking for the answer to the same question (How to set javascript value to jinja variable) because This tutorial on flask with charts shows you inserting a jinja variable into a java script. The problem is Java looks at the double bracket ( {{ VAR1 }} )as part of the script and throws errors.

The way you're describing, it can't be done.
Let's review Python, Jinja2, and JavaScript, because I think we can still achieve what you want.
Python is the language of your server, which will create the HTML sent to your clients.
Jinja2 is a templating engine for Python, which makes it easy to generate HTML without writing it directly. Notice that you're calling a function like render_template() in your backend. This generates the HTML using Jinja2 syntax, replacing Jinja2 statements with values known to the server, and inserting them into the HTML before it gets presented to the client. Think of Jinja2 as shorthand for variable insertion and simple scripting for making HTML.
JavaScript is your frontend scripting language, running on the client's browser once the HTML has been generated and served.
The reason you can't use Javascript to "set a Jinja2 variable" is because there are no Jinja2 variables in the rendered HTML sent to the client. Python and Jinja2 did that replacement on the server before sending the pure HTML/CSS/JS page to the client's browser.
Perhaps what you want to do though, is use frontend elements to change values that were initially set by python and Jinja2 on the backend. To do this, you will need to have your JavaScript send information back to the server, so the server can use this information to rerender the page, possibly inserting new values into your templates using Jinja2 in the process. Consider simply linking to a URL with the parameter you want to set.
You could link to www.yourwebsite.com?x=value, and now x will be set to 'value' in the backend. You can use this in your HTML template by including {{ x }}, which will resolve to 'value' when you call render_template()

Well... you could send a post request from your javascript to the server and then from your python backend send the information to the html frontend
javascript frontend > POST > python backend > TEMPLATE > html frontend

Related

Thymeleaf inline javascript expression with variable

I'm using Spring Boot with Thymeleaf, and know I can use variables from my controller on the following way in javascript:
<script th:inline="javascript">
/*<![CDATA[*/
var username = [[${#authentication.principal.person.isSubscribedTo("random string")}]];
/*]]>*/
</script>
Now I tried to use a local variable outside the CDATA comment like this. I expected I could use that in the method.
var randomString = "can i use this?";
/*<![CDATA[*/
var username = [[${#authentication.principal.person.isSubscribedTo(randomString)}]];
/*]]>*/
This does not work and I can't test this because my debugger won't get it the method and is not giving back any errors.
How can I use a local javascript variable in a thymeleaf javascript expression?
You're showing a bit of confusion about what's happening when and where.
First, the server uses Thymeleaf to generate the HTML and dynamic Javascript for a page. In this process, as you've said Thymeleaf can call into your Spring beans as it's running on the server.
Then, once the HTML & dynamic Javascript is sent to the browser, it runs the Javascript all client-side.
The only real approaches are:
Generate that randomString on the server side as well, within Thymeleaf or in the model accessible to Thymeleaf.
If you need to generate that string on the client side, have the Javascript make a separate HTTP request ("AJAX") call with that information to the server, and then do something reasonable with the response. That is to say, once the Javascript is sent to the browser, if you need to make more round trips to the server it's on the Javascript to ensure that it happens, as Thymeleaf's role in the page is done.

How to pass JSON from Django to Angular

Usually Angular get from HTTP request the JSON from server side (like Django).
But, to accelerate rendering, would like to write down on server side the JSON into a Javascript VAR and let proceed Angular on this javascript variable containing the JSON.
My question are:
1) How to pass this javascript var to angular $scope variable ?
(without HTTP).
2) Is writing down the JSON into the HTML a bad/good practice ?
(given my web app is fairly static).
You can do a simple $scope = {{ some_django_tag|safe }}. I can't see why it would be a bad practice if you're 100% sure that the output will be valid JS. I actually do this a bit to instantiate the scope on the page load.

what is the difference with "test" javascript variable and "#test" variable can i convert var javascript to "#test"

I've seen a servlet between the JSP and the database that is implemented similar this page. the important part for me is this:
param p1fd = new param();
p1fd.setVal(request.getParameter("formDDL"));
where the parameter in jsp code is referenced as "#formDDL"
the problem is that I have formDDL as a javascript variable as such:
var formDDL;
How can I convert the javascript variable to #formDDL?
Is there any other way to I pass this variable to Expression Language written for inserting in mySQL code?
The scriptlet part of the JSP is executed on the server side prior to it being returned to the client. Therefore you can't change its value after the page is sent to the client. You would have to have a preliminary page that sets the value of formDDL in javascript and then call into the server to request the page with the formDDL included as a request parameter or POST data. Basically the same approach that was done in the page you linked.
If you didn't want to have to fully reload the page to change the value of formDDL then you would have to take a completely different approach and look into using Ajax.
Also be mindful of SQL injection attacks when following a similar approach to the one you linked to.

JavaScript code on rails console

I use binding.pry in somewhere in Cabypara code for debugging, and i want to check the value of html element using jQuery.
I can't use debugger, then check the value from browser, because this code is Cabybara code for testing as example:
When /^(?:|I )select "([^"]*)" from "([^"]*)"$/ do |value, field|
select(value, :from => field)
binding.pry
end
How can i check the value of this field by jQuery code as $("##{field}").val() on rails console ?
This answer depends on #apneadiving's comment:
Rails console used for server side only, not for client side, these helper links:
Ruby-on-Rails is server side.
Rails console is useful for testing out quick ideas with code and changing data server-side without touching the website.
You can call binding.pry while Rails is rendering your view, even in the javascript portion of the view.
This is not going to give you access to the the client side code. Like #apneadiving and #mohamed-yakout stated you can't access the client from the server, but it can give the the access to all of the server side information that is available at that moment in the rendering process.
erb:
<script>
// some javascript...
"<% binding.pry %>"
</script>
// Note: You can not do this from `.js` files that are assets of the view without
// adding the `.erb` extension to the javascript files.
This may be helpful in checking values being utilized by JQuery or Javascript and verifying that they are being built correctly at this step in the process. Ex: verifying the collection being used to generate the rows of a table
In your case you could verify the value of field, but not the value of the element found by the id being passed by the field variable.
$("##{field}").val()
This can be helpful when the result of "##{field}" is giving an #unexpected result instead of an #expected one, since you can't access the server side code from the client to determine the rendering problem.
Note: This translates to Slim as well
javascript:
// some javascript...
"#{binding.pry}"

pyfacebook and javascript query

I'm using pyfacebook on the backend and javascript on the client side. Now if I want to pass a variable to the javascript from pyfacebook. how would I go about doing that, any ideas?
You can't pass a variable directly, as JavaScript is running on the client (browser), and Python is running on the server.
You could make a XHR (AJAX) request from JavaScript to the server which would then return your values back to JS (JSON could be used here).
Or you could put a hidden field to your markup that would have the value in it's "value" attribute. You could then read that with JavaScript.
ps: your question really isn't related to pyfacebook but Python (or any other server side technology) in general and that has been covered here many many times.

Categories

Resources