Html header 불러오기 - html header bulleoogi

Html header 불러오기 - html header bulleoogi

include(인클루드) 란?

기존에 입력한 소스를 불러와 작업 페이지에서 이미작업된 페이지를 가져다 활용함으로 작업했던 내용을 또 작업하는 내용이 없도록 시간적 공간적 절약을 위해 사용된다.

include(인클루드) 왜 사용되는가?

코딩시에 프로젝트 전반적으로 자주 사용되는 반복 구간을 매번 새로운 소스를 입력하여 작업하는건 시간적으로도 프로젝트내에서도 좋지않고, 소스를 새로입력하는것보다, 기존에 입력되어있는소스를 리딩하여 해당소스는 공통적으로 통합 관리하기 위함으로 사용됩니다.

include(인클루드) 사용법?

HTML

<script src="//code.jquery.com/jquery-1.11.0.min.js">
</script>
<script type="text/javascript">   
$(document).ready( function() {
					$("#headers").load("common/header.html");  //헤더 인클루드
					$("#footers").load("common/footer.html");  //푸터부분 인클루드
								}
					);
</script>


<div id="headers"></div>

<div id="footers"></div>

PHP

--상대경로시
<? include("../경로.php");?>
--절대경로시
<?php include("../경로.php");?>

ASP

'상대경로시
<!-- #include file="../경로명.asp"-->

'절대경로시
<!-- #include virtual="/경로명.asp"-->

JSP

<%@ include file="../경로.jsp" %

<jsp:include page="../상대 또는 절대경로.jsp" flush="true" />

header 와 footer 같은 html파일은 고정적으로 들어가기 때문에 따로 html파일로 작성 후 가져오는것이 좋다.

js를 이용하여 html파일을 가져올 수 도 있지만 flask를 통해 html문서를 html문서 안에 넣는 방법도 있다.

아래와 같이 html문서 안에 {% include '가져올 파일명.html' %} 형식으로 가져오면 된다.

<body>
    <header>{% include 'header.html' %}</header>
    <footer>{% include 'footer.html' %}</footer>
</body>

html 안에 html을 넣고 싶었다.

html로 문서를 작성 중이었는데 하나의 파일이 너무 지저분해지는 것 같아서 각 세부내용들은 다른 파일에 작성하고 불러오는 것이 목적이었다.

Html header 불러오기 - html header bulleoogi

위처럼 contents라는 id를 가진 div 안에 contents.html에 작성된 내용을 넣고 싶었다.

Javascript의 fetch를 이용해서 html text를 가져와 innerHtml을 이용하면 손쉽게 해결할 수 있었다.

물론 이 방법은 index.html을 그냥 브라우저에서 여는 형식으로는 동작하지 않는다. fetch를 이용하는 방법이기에 이 글을 읽는 사람이라면 알고 있을 것이다.

async function fetchHtmlAsText(url) {
    return await (await fetch(url)).text();
}

async function importPage(target) {
    document.querySelector('#' + target).innerHTML = await fetchHtmlAsText(target + '.html');
}

위의 두 가지 함수만 이용하면 id로 요소를 검색한 뒤 해당 요소 안에 id와 동일한 파일명의 html을 넣을 수 있다.

Html header 불러오기 - html header bulleoogi

이렇게 사용하면

Html header 불러오기 - html header bulleoogi


contents라는 id를 가진 div 안에 contents.html의 내용이 들어가는 것을 확인할 수 있다.


Reference

  • stack overflow, How do I load an HTML page in a div using JavaScript?

function includeHTML(){

let z, elmnt, file, xhttp;

= document.getElementsByTagName("*");

for (let i = 0; i < z.length; i++) {

elmnt = z[i];

file = elmnt.getAttribute("data-include");

if (file) {

xhttp = new XMLHttpRequest();

xhttp.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("data-include");

includeHTML();

}//if

}//onreadystatechange

xhttp.open("GET", file, true);

xhttp.send();

return;

}//if - file

}//for

}//includeHTML

/* ✨ 실행 */

window.addEventListener('DOMContentLoaded',()=>{

includeHTML();

});