everyday com-eat
작성일
2023. 12. 12. 00:03
작성자
갱수터
728x90

템플릿 기능 정리

  • 객체지향 방식으로
  •  templateHTML, templateList 함수(성격이 같은 것들을 그룹화 하기 위해 접두사나 접미사를 사용하곤 함)

 

template 객체 정의

...생략

var template = {
  HTML: function(title, list, body, control) {
    return `
      !doctype html>
      <html>
        <head>
          <title>WEB1 - ${title}</title>
          <meta charset="utf-8">
        </head>
        <body>
          <h1><a href="/">WEB</a></h1>
          ${list}
          ${control}
          ${body}
        </body>
      </html>
    `;
  },
  list: function(filelist) {
    var i = 0;
    var list = '<ul>';
    while(i < filelist.length) {
      list += `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
      i++;
    }
    list += '</ul>';
    return list;
  }
}
var app = http.createServer(function(request, response) {

...생략...

 

 

 

함수 호출하는 부분 수정

var title = 'Welcome';
var description = 'Hello, Node.js';
var list = template.list(filelist);	//templateHTML >>> template.list
var html =template.HTML(title, list,	//template >>> html,  templateHTML >>> template.list
  `<h2>${title}</h2><p>${description}</p>`,
  `<a href="/create">create</a>`);

response.writeHead(200);
response.end(html);	//template >>> html

 

 


 

 

모듈

  • 코드를 정리하는 가장 큰 도구(객체나 함수를 정리정돈할 수 있는 개념)라 할 수있음

 

객체 내보내는 모듈 modul.exports

var M ={
    v:'v',
    f:function() {
        console.log(this.v);
    }
}

module.exports = M;

 

 

객체 가져오는 모듈 require

var part = require('./mpart');
console.log(part);
part.f();

결과

 

 

 

모듈 활용

  • template 객체  >>> template.js 외부파일로 만들기
  • 변수지정을 따로 안하고 아예 변수이름 자리에  module.exports 써도 됨
  • template.js 파일 require 해주기 
var template = require('./lib/template.js');

 

 

728x90