Can js script get a variable written in context / EJS page in the same file

As I wrote in the title, I would like to get the value from the variable written on the page / ejs file, from the javascript file on the same page

EJS:

<% var test = 101; %> 

JS:

 <script> var getTest = test; </script> 

Or what if I would like to use a function (with a parameter) written to an EJS file and use this function in a JS context, where the parameter is assigned to a function from the JS context

EJS:

 <% function fn(par){ ... } %> 

JS:

 <script> var test = 101; <%>fn(test)<%> </script> 
+11
source share
2 answers

Edit : this half believes that you are using server- side EJS

1) You can pass the value of the ejs variable to a Javascript variable

  <% var test = 101; %> // variable created by ejs <script> var getTest = <%= test %>; //var test is now assigned to getTest which will only work on browsers console.log(getTest); // successfully prints 101 on browser </script> 

just create an ejs variable and assign a value inside the script tag var getTest script

Example: var getTest = <%= test %>;

2) You cannot pass the value of javascript variable to ejs variable

Yes, you cannot: if it is on the server.

Why:

The EJS template will be displayed on the server until Javscript is launched (it will be launched in the browser), so the server will not return to the server and ask for some previous changes on the page that has already been sent to the browser page.


Edit : this half believes that you are using EJS on the Client side

3) if EJS is on the client side and passes the EJS variable to javascript

The above answer will still work, but you will need to load the script into the EJS template , not the script loaded before the created template (in this case, of course, it will not be valid javascript).

4) if EJS is on the client side and passes the javascript variable to EJS

I'm sorry that I myself have not tried this case, but I really wait if someone answers this case

+17
source

The above answer does not work for me. You can use div as follows:

 <div id="mydiv" data-test=<%= test %>></div> 

And access to the data variable 'test' that you gave in the script tag:

 <script>var test = document.getElementById('mydiv').dataset.test</script> 

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

+1
source

Source: https://habr.com/ru/post/1213694/


All Articles