In an application written by express, you can pass a variable to a template like this:

router.get('/test', function (req, res, next) { var test = 9; res.render('main/login', { testVar: test }); }); 

How to transfer a variable to a javascript file?

  • Where do you want to transfer variables from? And which js file exactly? - Dmitriy Simushev
  • Transfer to js file on the client. In the template engine ejs, I output the variable like this: <% = testVar%> and how to get this variable in js - darut

1 answer 1

The task of transferring configuration parameters from the server application to the client occurs regularly. In most cases, it is more correct to make a certain function that initializes the client application, and in the process of rendering the page, to transfer this function an object with configuration parameters.

As for the EJS, it supports the syntax <%- data %> , which allows you to disable auto-trace. Together with JSON.stringify this completely solves the problem of transferring data to the client application.

For example, your template might look like:

 <html> <head> <title><%= title %></title> <script type="text/javascript"> // Π­Ρ‚ΠΎΡ‚ ΠΊΠΎΠ΄ стоит вынСсти Π² ΠΎΡ‚Π΄Π΅Π»ΡŒΠ½Ρ‹ΠΉ Ρ„Π°ΠΉΠ». var initApp = function(options) { // ... Π›ΠΎΠ³ΠΈΠΊΠ° ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ клиСнтского прилоТСния. console.log(options.foo); console.log(options.bar); } </script> <script type="text/javascript"> // Π˜Π½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΡƒΠ΅ΠΌ клиСнтскоС ΠΏΡ€ΠΈΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅ с Π΄Π°Π½Π½Ρ‹ΠΌΠΈ, ΠΏΠ΅Ρ€Π΅Π΄Π°Π½Π½Ρ‹ΠΌΠΈ // ΠΈΠ· сСрвСрного прилоТСния. initApp(<%- appConfigs %>); </script> </head> <body> <!-- Π—Π΄Π΅ΡΡŒ ΠΌΠΎΠ³Π»Π° Π±Ρ‹Ρ‚ΡŒ ваша Ρ€Π°Π·ΠΌΠ΅Ρ‚ΠΊΠ° --> </body> </html> 

And the code involved in rendering may be:

 var ejs = require('ejs'), template = '...'; var appConfigs = { foo: 'bar', bar: 'baz' }; ejs.render(template, { title: 'An awesome page!', appConfigs: JSON.stringify(appConfigs) });