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?
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?
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) }); Source: https://ru.stackoverflow.com/questions/514284/
All Articles