Web 관련/HTML

HTML 파일 분리하는 법. HTML에서 다른 HTML 포함시키는 법.

iKay 2019. 3. 9. 12:25
반응형

0. 들어가기 전

얼마 전 개인적으로 웹 프로젝트를 진행하던 중 'HTML파일을 분리할 수 없을까' 라는 궁금한 점이 한 가지 생겼다. 웹 프로젝트 경험이 풍부하지는 않지만 직감적으로 HTML파일을 분리할 수 있다면 분명 개발&수정이 쉽고 협업하기 좋을 것이 때문이다. 개인적인 생각이지만 웹 프론트엔드 프레임워크가 요즘 유행하는 이유도 이와 같이 웹 페이지를 모듈처럼 분리하려는 시도에서 유래됐을 것이라 생각한다.  

  

다른 프론트엔드 프레임워크를 사용하지 않고도 생각보다 쉽게 HTML 파일을 분리할 수 있었고 그 방법과 장점에 대해 포스팅한다. 

 

1. 웹 페이지를 하나 만들어 보자

예를 들어 아래와 같은 웹 하나 만든다 가정해 보자. 

 

 

2. HTML 파일을 분리하지 않으면?

코드로 보자. index.html이 <header>, <footer>, <nav>, <article> tag를 포함할 경우, 아래와 같이 index.html을 작성할 수 있겠다. css부분은 생략했다. 

 

<!DOCTYPE html>

<head>
    <meta charset="UTF-8">
    <title>분리되지 않은 HTML</title>
</head>

<body>
    <header>
        <h1>분리되지 않은 HTML</h1>
    </header>
    <nav>
        <ul>
            <li>section 1</li>
            <li>section 2</li>
            <li>section 3</li>
            <li>section 4</li>
            <li>...</li>
            <li>section n</li>
        </ul>
    </nav>
    <article>
        <div id="section-n">
            content for section n
        </div>
    </article>
    <footer>
        <div>
            this is footer
        </div>
    </footer>
</body>

</html>

 

이렇게 코딩하면 문제점이 무엇일까? 

 

1) 코드가 길어져서 가독성이 떨어진다. 

2) 동시에 각 tag 작업이 어렵다. 

 

따라서 이 문제를 해결하기 위해 html tag를 파일로 분리해보고자 한다. 

 

3. 파일을 분리하는 방법

방법은 여기[각주:1] 웹 페이지의 소스코드를 거의 그대로 썼다. 원문을 보고 싶다면 들어가서 보자. 

 

이 예제를 수행하기 위해서는 웹 서버를 따로 하나 띄우고 아래와 같은 static 파일을 제공하도록 만들어야 한다. nodejs, python 등으로 쉽게 웹 서버를 띄울 수 있을 것이니 이 부분에 대한 설명은 생략한다.   

 

작업 디렉토리를 구성하면 다음과 같다.

 

public ㅡ ㅡ html ㅡㅡ index.html

            |                      ㄴㅡ header.html

            |                      ㄴㅡ nav.html

            |                      ㄴㅡ article.html

            |                      ㄴㅡ footer.html

            | 

            ㄴㅡㅡ js ㅡㅡ includeHTML.js

  

 

소스 코드를 보자. 마찬가지로 css부분은 생략했다. 

 

index.html

<!DOCTYPE html>

<head>
    <meta charset="UTF-8">
    <title>분리된 HTML</title>
    <script src="/static/js/includeHTML.js"></script>
</head>

<body>
    <header include-html="/static/html/header.html"></header>
    <nav include-html="/static/html/nav.html"></nav>
    <article include-html="/static/html/article.html"></article>
    <footer include-html="/static/html/footer.html"></footer>
</body>
<script>
    includeHTML();
</script>

</html>

 

header.html

<h1>분리된 HTML</h1>

 

nav.html

<ul>
    <li>section 1</li>
    <li>section 2</li>
    <li>section 3</li>
    <li>section 4</li>
    <li>...</li>
    <li>section n</li>
</ul>

 

footer.html

<div>
    this is footer
</div>

 

includeHTML.js

 

// [참고] https://www.w3schools.com/howto/howto_html_include.asp

function includeHTML(callback) {
  var z, i, elmnt, file, xhr;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("include-html");
    //console.log(file);
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {
            elmnt.innerHTML = this.responseText;
          }
          if (this.status == 404) {
            elmnt.innerHTML = "Page not found.";
          }
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("include-html");
          includeHTML(callback);
        }
      };
      xhr.open("GET", file, true);
      xhr.send();
      /*exit the function:*/
      return;
    }
  }
  setTimeout(function() {
    callback();
  }, 0);
}

 

includeHTML.js 소스코드를 조금 살펴보자. includeHTML( )은 웹 페이지에서 모든 element 중 'include-html'이라는 attribute가 있는 경우 재귀적으로 수행되면서 파일을 불러온다. 

 

이렇게 분리시킴으로서 코드의 가독성과 작업의 동시성을 높일 수 있다. 

 

4. 소스코드

https://github.com/hgs0426/my-html-template

 

5. 마치며

html 태그를 파일로 분리함으로서 많은 장점은 얻었지만 분리된 구조에서 section과 article을 잇는 방법은 아직 설명 못했다. 만약 이것을 해결하지 못한다면 최악으로는 section 만큼 웹 페이지를 반복해서 만들어야 할 수 있다... 그래서 다음 포스팅에서는  section 별로 article을 라우팅(routing) 하는 법을 게재할 예정이다.  

 

  

 

  1. [2] https://www.w3schools.com/howto/howto_html_include.asp [본문으로]
반응형