Question

I want to use node varible in html file which node.js is loading. Here is my code.

var cord  = [ '37.772323,-122.214897','21.291982,-157.821856','-18.142599,178.431',
'-27.46758,153.027892' ]

fs.readFile('./map.html', function (err, html) {
    if (err) {
    throw err; 
    }       
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(8000);
});

I want to use variable cord in in map.html. any suggestion please.

Était-ce utile?

La solution

To pass variables from node to html you should either write your own template engine, or use third party solution (like EJS).

To install EJS, open terminal, go to desired directory, and type npm install ejs

Your server-side code may look like this:

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');

var content = fs.readFileSync('./map.ejs', 'utf-8');
var compiled = ejs.compile(content);

var cord  = [ '37.772323,-122.214897','21.291982,-157.821856','-18.142599,178.431','-27.46758,153.027892' ]

http.createServer(function(request, response) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.write(compiled({cord: cord}));
    response.end();
}).listen(8000);


And here is the example of map.ejs:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(function() {
    var cord = $.parseJSON($('#cord').val());
    alert(cord);
});
</script>
</html>
<body>

    <textarea id="cord" style="display:none;"><%=JSON.stringify(cord)%></textarea>

</body>
</html>


And after opening http://localhost:8000 in browser you will see an alert showing cord array.

More information about EJS you may find in the documentation:
https://github.com/visionmedia/ejs
http://embeddedjs.com/

Good luck!

EDIT

EJS is not the only template engine for node. Consider also Jade.
And here is a (bit outdated) list of other template engines. Choose the one you like :)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top