Template Language

웹 초창기 - CGI


int main(void)
{
  char *data;
  long m,n;
  printf("%s%c%c\n", "Content-Type:text/html",13,10);
  printf("<TITLE>Multiplication results</TITLE>\n");
  printf("<H3>Multiplication results</H3>\n");
  data = getenv("QUERY_STRING");
  if(data == NULL)
    printf("<P> Error in passing data from form to script.");
  else if(sscanf(data,"m=%ld&n=%ld",&m,&n)!=2)
    printf("<P>Error! Invalid data. Data must be numeric.");
  else
    printf("<P>The product of %ld and %ld is %ld.",m,n,m*n);
  return 0;
}
        

Template Engine

  • 템플릿과 데이터를 결합해 문서를 생성하는 프로그램, 혹은 라이브러리
  • 템플릿을 작성할 때 사용하는 언어를 템플릿 언어라고 함

EJS

Embedded JavaScript Template #

Example


<%# index.ejs %>
<html>
  <head>
    <title><%= title %></title>
  </head>
  <body>
    <div class="message">
      <%= message %>
    </div>
    <% if (showSecret) { %>
      <div>my secret</div>
    <% } %>
  </body>
</html>
        

Express에서 EJS 사용하기

  • ejs 설치
    
    $ npm install --save ejs
                
  • template engine 설정
    
    app.set('view engine', 'ejs')
                
  • res.render()
    
    const data = {
      title: 'Template Language',
      message: 'Hello EJS!',
      showSecret: true
    }
    res.render('index.ejs', data)
                

EJS 예제

Link

파일을 그대로 제공하기


// `public` 폴더에 있는 파일을 `/static` 경로 아래에서 제공
app.use('/static', express.static('public'))
        

<!-- 템플릿 파일에서 참조할 수 있음 -->
<link rel="stylesheet" href="/static/index.css">
<script type="text/javascript" src="/static/index.js"></script>
        

EJS 실습

Link