[NodeJs] 외부모듈사용하기 - EJS 모듈

2021. 4. 29. 18:19 JavaScript BackEnd/Node.js, Express

EJS (Embedded JavaScript (http://embeddedjs.com)

Template Engine

 

1. 설치하기 

npm install ejs

 

2. 사용하기

EJS 특수태그

<% code %>

<%= value %>

 

3. 예제 코드

ejstest.js

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

var server = http.createServer(function(req, res) {
	data = {name: 'lee', age:27};
	fs.readFile('./test.ejs.html', 'utf-8', function(err,file) {
		console.log(file);
		var html = ejs.render(file,data);
		res.writeHead(200, {"Content-Type":"text/html"});
		res.end(html);
	});
});
server.listen(8888, function() {
	console.log('server running on 8888.');
});

test.ejs.html

<h1>EJS Test page.</h1>
<!-- execution -->
<% for(var i = 0; i < 10; i ++) {%>
<!-- assign -->
<div>Name : <%=name%>, Age : <%=age%></div>
<% } %>

 

4. 실행화면

 

출처 : ourcstory.tistory.com/7?category=664896