html 인클루드하기 grunt-includes

실무에서 작업을 할때는 html 을 다루다가 개발단계로 넘어가면 서버환경에 따라 php, jsp, asp 등 언어가 바뀝니다.

또 html 을 다룰때 include 가 꼭 필요합니다. 필요이상의 코드를 줄이고, 나중에 수정 또한 편하기 때문입니다.

html 파일전체를 조각 조각 나누어서 include 시키고 본문 컨텐츠만 작성하는 방법을 사용합니다.

인클루드 시키는 파일을 보면 대략, doctype 에서 </head> 닫는곳까지 하나의 인클루드 파일 head.html 로 만든다. 또, gnb, lnb, breadcrumbs, footer, js부분 등 즉 본문컨텐츠를 제외한 모든 부분을 조각조각내어 인클루드 시킨다.

문제는 서버환경에 따라 인클루드문이 조금씩 다르고, 서버환경이 되어 있어야 한다는 단점이 있습니다.

이걸 해결하는 방법이 없을까 고민하다가 grunt 를 사용할때 include 를 사용하는 좋은 모듈이 있어 소개합니다.

사용목적

  • 서버 환경 설정이 필요없다.
  • 서버 언어가 필요없다.
  • 친숙한 html 을 그대로 사용할 수 있다.
  • include 문을 사용할 수 있다.

grunt-includes

grunt-includes 의 장점은 파일내에 다른 파일을 포함할수 있습니다. 또한 모든 부모와 자식들의 들여쓰기를 유지합니다.


먼저 설치해보자.

npm install grunt-includes --save-dev

두번째로 설정을 해야된는데 설명이 필요함으로 맨 나중에 하겠습니다.

세번째로 gruntfile.js에 task 를 설정한다.

grunt.loadNpmTasks('grunt-includes');

네번째로 실행에 필요한 registerTask 를 아래의 예제처럼 넣어준다. 아래는 예제.

grunt.registerTask('dev', 'includes');

자 이제 설정을 어떤식으로 하는지 알아보자. 옵션과 사용법은 홈페이지에 나와 있으니 참고하세요. 또한 example 를 통해 어떤식으로 되어있는지 알아보자.

example 의 폴더구조가 상당이 중요하다. 먼저 폴더 구조를 보자.

|   .gitignore
|   Gruntfile.js
|   License
|   package.json
|   Readme.md
|
+---assets
|   \---less
|           site.less
|
+---build
|   |   index.html
|   |
|   +---css
|   |       app.css
|   |
|   \---pages
|           about.html
|
+---include
|       footer.html
|       header.html
|
\---site
    |   index.html
    |
    \---pages
            about.html

site 폴더 - 이 폴더가 작업폴더다. 즉 include 문이 들어가는 html 파일이 모두 여기에 있다고 생각하면 된다. 마찬가지로 site폴더안에 형재폴더로 pages 폴더를 사용할 수도 있고 그 안에 about.html 도 보인다.

include 폴더 - 이 폴더의 파일들이 include 문에 의해서 포함되는 파일이다. site폴더에서 include 문을 사용해서 작업할때 이 폴더의 파일을 인클루드한다. 보시면 header 부분, footer 부분이 포함된다. 물론 얼마든지 조각, 조각 내어서 사용할 수 있다.

build 폴더 - 이 폴더가 완성된 파일들이 있는 폴더다. 즉 완전한 html 파일들이 있는 폴더다.

간단이 정리해보면 site폴더가 작업폴더이고, include폴더의 파일을 인클루드하고 완성되면 build 폴더에 만들어지게 된다.

구문을 보자

어떤식으로 인클루드문을 사용하는지 site 폴더의 index.html 의 body 부분을 보자.

<body>
  include "header.html"

  <div class="container" role="main">

    <p>I am the main container of the page!</p>

  </div>

  include "footer.html"
</body>

include 구문은 간단하다.

include "파일명"

이게 끝이다.

포함되는 파일은 include 폴더에 넣어두면 된다.

여기서 주의깊게 봐야하는 부분은 gruntfile.js 의 includePath 다.

아래 gruntfile.js 의 includes 부분을 보자.

includes: {
    build: {
        cwd: 'site',
        src: [ '*.html', 'pages/*.html' ],
        dest: 'build/',
        options: {
        flatten: true,
        includePath: 'include',
        banner: '<!-- Site built using grunt includes! -->\n'
        }
    }
}

여기 구문을 풀이하자면 site 폴더의 파일을 build 폴더에 빌드시켜서 만들어냅니다.
그런데 includePath: 'include' 가 되어 있으므로 인클루드되는 파일을 모두 include폴더에 있어야 합니다.

builde 폴더에 완성된 index.html 을 보면 아래와 같습니다.

<body>
  <header role="header">
    <h4>Hello from the header!</h4>

    <nav>
      <ul>
        <li><a href="pages/about.html">About</a></li>
      </ul>
    </nav>
  </header>

  <div class="container" role="main">

    <p>I am the main container of the page!</p>

  </div>

  <footer role="footer">
    <p>Hello from the footer!</p>

    <h4>License</h4>
    <code>
      Copyright (c) 2013 Matt McFarland

      Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    </code>
  </footer>
</body>