Posts

Showing posts with the label Ejs

Can I Use Conditional Statements With EJS Templates (in JMVC)?

Answer : For others that stumble on this, you can also use ejs params/props in conditional statements: recipes.js File: app.get("/recipes", function(req, res) { res.render("recipes.ejs", { recipes: recipes }); }); recipes.ejs File: <%if (recipes.length > 0) { %> // Do something with more than 1 recipe <% } %> Conditionals work if they're structured correctly, I ran into this issue and figured it out. For conditionals, the tag before else has to be paired with the end tag of the previous if otherwise the statements will evaluate separately and produce an error. ERROR! <% if(true){ %> <h1>foo</h1> <% } %> <% else{ %> <h1>bar</h1> <% } %> Correct <% if(true){ %> <h1>foo</h1> <% } else{ %> <h1>bar</h1> <% } %> hope this helped. Yes , You can use conditional statement with EJS like if else , ternary operat...

Can A Js Script Get A Variable Written In A EJS Context/page Within The Same File

Answer : Edit : this Half considers you are using EJS on server side 1) You can pass an ejs variable value 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> simply create an ejs variable and assign the value inside the script tag to the var getTest Ex: var getTest = <%= test %>; 2) You can't pass an javascript variable value to a ejs variable Yes, you cant: if it is on server. Why: The EJS template will be rendered on the server before the Javscript is started execution(it will start on browser), so there is no way going back to server and ask for some previous changes on the page which is already sent to the browser. Edit : this Half considers you are using EJS on Client...

Accessing EJS Variable In Javascript Logic

Answer : You could directly inject the gameState variable into javascript on the page. <% if (gameState) { %> <h2>I have a game state!</h2> <script> var clientGameState = <%= gameState %> </script> <% } %> Another option might be to make an AJAX call back to the server once the page has already loaded, return the gameState JSON, and set clientGameState to the JSON response. You may also be interested in this: How can I share code between Node.js and the browser? I had the same problem. I needed to use the data not for just rendering the page, but in my js script. Because the page is just string when rendered, you have to turn the data in a string, then parse it again in js. In my case my data was a JSON array, so: <script> var test = '<%- JSON.stringify(sampleJsonData) %>'; // test is now a valid js object </script> Single quotes are there to not be mixed with double-q...