IT

여러 HTML 페이지에 포함 할 머리글 및 바닥 글 파일 만들기

lottoking 2020. 7. 13. 07:50
반응형

여러 HTML 페이지에 포함 할 머리글 및 바닥 글 파일 만들기


여러 HTML 페이지에 포함 된 공통 머리글 및 바닥 글 페이지를 만들고 싶습니다.

자바 펼쳐를 사용하고 싶습니다. html과 JavaScript 만 사용하여 수행하는 방법이 있습니까?

다른 html 페이지를 머리글 및 바닥 글 페이지를로드하고 싶습니다.


jquery 로이를 수행 할 수 있습니다 .

이 코드를 index.html

<html>
<head>
<title></title>
<script
    src="https://code.jquery.com/jquery-3.3.1.js"
    integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
    crossorigin="anonymous">
</script>
<script> 
$(function(){
  $("#header").load("header.html"); 
  $("#footer").load("footer.html"); 
});
</script> 
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>

그리고이 코드를 삽입 header.htmlfooter.html같은 위치로에,index.html

<a href="http://www.google.com">click here for google</a>

이제를 방문 index.html하면 링크 태그를 클릭 할 수 있습니다.


서버 측에는 공통 부분을 머리글 및 바닥 글로 추가 합니다. HTML이나 JavaScript가 필요하지 않습니다. 대신 웹 서버는 다른 작업을 수행하기 전에 포함 된 코드를 자동으로 추가합니다.

파일을 포함 할 위치에 다음 줄을 추가하십시오.

<!--#include file="include_head.html" -->

JavaScript와 함께 html 파일 구조를 가지고 있습니까? 간단한 PHP는 PHP를 대신 사용할 수 있습니다.

.html 페이지의 파일 이름을 .php로 변환하면 각 .php 페이지의 맨 위에 한 줄의 코드를 사용하여 header.php의 내용을 포함 할 수 있습니다.

<?php include('header.php'); ?>

footer.php 파일의 내용을 포함 시키려면 각 페이지의 바닥 글에서 동일하게 수행하십시오.

<?php include('footer.php'); ?>

JavaScript / Jquery 또는 추가 포함 파일이 필요하지 않습니다.

NB .htaccess 파일에서 다음을 사용하여 .html 파일을 .php 파일로 변환 할 수도 있습니다.

# re-write html to php
RewriteRule ^(.*)\.html$ $1.php [L]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]


# re-write no extension to .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

나는 시도 시도했다 : 같은 파일 header.html 만들기

<!-- Meta -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- JS -->
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/lib/angular-route.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">

<title>Your application</title>

이제 다음 과 같이 HTML 페이지에 HEADER.html 현재 현재포함 하십시오.

<head>
   <script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
   <script> 
     $(function(){ $("head").load("header.html") });
   </script>
</head>

완벽하게 작동합니다.


(load_essentials.js :)를 넣을 수도 있습니다.

document.getElementById("myHead").innerHTML =
	"<span id='headerText'>Title</span>"
	+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
	"<ul id='navLinks'>"
	+ "<li><a href='index.html'>Home</a></li>"
	+ "<li><a href='about.html'>About</a>"
	+ "<li><a href='donate.html'>Donate</a></li>"
	+ "</ul>";
document.getElementById("myFooter").innerHTML =
	"<p id='copyright'>Copyright &copy; " + new Date().getFullYear() + " You. All"
	+ " rights reserved.</p>"
	+ "<p id='credits'>Layout by You</p>"
	+ "<p id='contact'><a href='mailto:you@you.com'>Contact Us</a> / "
	+ "<a href='mailto:you@you.com'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>

<script src="load_essentials.js"></script>


C # / Razor에서 일하고 있는데 가정용 랩톱에 IIS를 설치하지 갑자기 기 때문에 프로젝트에 정적 마크 업을 만드는 동안 뷰에서로드 할 자바 펼쳐 솔루션을 찾았습니다.

나는 "jquery를 버리는 방법"을 설명하는 웹 사이트를 우연히 발견했다.이 사이트의 메소드는 일반 Jane 자바 펼쳐 ( post 하단의 참조 링크)에서 정확히 무엇을 보여줍니다 . 사용 환경에서 사용하려는 경우 보안 취약성 및 문제를 조사하십시오. 나는 아니에요, 그래서 나는 그것을 직접 들여다 볼 수 있습니다.

JS 기능

var getURL = function (url, success, error) {
    if (!window.XMLHttpRequest) return;
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === 4) {
            if (request.status !== 200) {
                if (error && typeof error === 'function') {
                    error(request.responseText, request);
                }
                return;
            }
            if (success && typeof success === 'function') {
                success(request.responseText, request);
            }
        }
    };
    request.open('GET', url);
    request.send();
};

내용을 얻으십시오

getURL(
    '/views/header.html',
    function (data) {
        var el = document.createElement(el);
        el.innerHTML = data;
        var fetch = el.querySelector('#new-header');
        var embed = document.querySelector('#header');
        if (!fetch || !embed) return;
        embed.innerHTML = fetch.innerHTML;

    }
);

index.html

<!-- This element will be replaced with #new-header -->
<div id="header"></div>

views / header.html

<!-- This element will replace #header -->
<header id="new-header"></header>

소스는 내 자신의 도구 OP에 대한 좋은 바닐라 자바 ​​서비스 솔루션 참조 참조하고 있습니다. 원래 코드는 여기에 있습니다. http://gomakethings.com/ditching-jquery#get-html-from-another-page


나는이 질문에 대한 답변이 너무 오래 전에 생각합니다 ... 현재 일부 및 모바일 브라우저는 이 작업을 위해 HTML 템플릿지원 합니다.

나는 작은 예를 만들었습니다.

테스트 OK 크롬 61.0, 오페라 48.0, 오페라 네온 1.0, 안드로이드 브라우저 6.0, 크롬 모바일 61.0와 Adblocker 브라우저 54.0에서
KO를 테스트 사파리 10.1, 파이어 폭스 56.0, 에지 38.14 및 IE (11)

canisue.com의 추가 추가 정보

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML Template Example</title>

    <link rel="stylesheet" href="styles.css">
    <link rel="import" href="autoload-template.html">
</head>
<body>

<div class="template-container">1</div>
<div class="template-container">2</div>
<div class="template-container">3</div>
<div class="template-container">4</div>
<div class="template-container">5</div>

</body>
</html>

autoload-template.html

<span id="template-content">
    Template Hello World!
</span>

<script>
    var me = document.currentScript.ownerDocument;
    var post = me.querySelector( '#template-content' );

    var container = document.querySelectorAll( '.template-container' );

    //alert( container.length );
    for(i=0; i<container.length ; i++) {
        container[i].appendChild( post.cloneNode( true ) );
    }
</script>

styles.css

#template-content {
    color: red;
}

.template-container {
    background-color: yellow;
    color: blue;
}

HTML5 Rocks 게시물 에서 더 많은 예제를 얻을 수 있습니다.


헤더에 펼쳐 링크를로드 할 수도 있습니다. 위의 예 중 하나를 추가하겠습니다.

<!--load_essentials.js-->
document.write('<link rel="stylesheet" type="text/css" href="css/style.css" />');
document.write('<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />');
document.write('<script src="js/jquery.js" type="text/javascript"></script>');

document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright &copy; " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:you@you.com'>Contact Us</a> / "
+ "<a href='mailto:you@you.com'>Report a problem.</a></p>";

<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>

<script src="load_essentials.js"></script>

2018 년의 알로하. 안타깝게도 여러분과 공유 할 멋지거나 미래 지향적 인 것이 없습니다.

그러나 현재 jQuery load()메소드가 작동하지 않는다고 언급 한 사람들 은 로컬 웹 서버를 실행하지 않고 로컬 파일과 함께 메소드를 사용하려고합니다. 이렇게하면 발생합니다로드 메소드에 의해 그는 같은 프로토콜 체계에 대한 지원으로 크로스 기원은 요청하는 지정 참조 한 "크로스 기원"오류, 위의 http, data또는 https. (실제 교차 출처 요청을하지 않고 가정합니다. 즉, header.html 파일이 실제로 요청한 페이지와 동일한 도메인에 있습니다.)

즉, 위의 답변이 작동하지 않는 경우 웹 서버를 실행하고 있는지 확인하십시오. 서두르고있는 경우 (그리고 Python이 사전에 설치된 Mac을 사용하는 경우)이를 수행하는 가장 간단한 방법은 간단한 Python http 가동하는 것입니다. 여기 에서 그렇게하는 것이 얼마나 쉬운 지 알 수 있습니다 .

이게 도움이 되길 계속!


이 질문이 처음 요청 된 이후로 사용 가능한 또 다른 접근 방식 참조는 reactrb-express를 사용하는 것입니다 ( http://reactrb.org ). 이렇게하면 클라이언트 측에서 Ruby로 펼쳐서 작성하여 html 코드를 Ruby로 계속 React 구성 요소로 대체 ​​할 수 있습니다.


.html 파일에 포함 할 HTML을 저장합니다.

Content.html

<a href="howto_google_maps.asp">Google Maps</a><br>
<a href="howto_css_animate_buttons.asp">Animated Buttons</a><br>
<a href="howto_css_modals.asp">Modal Boxes</a><br>
<a href="howto_js_animate.asp">Animations</a><br>
<a href="howto_js_progressbar.asp">Progress Bars</a><br>
<a href="howto_css_dropdown.asp">Hover Dropdowns</a><br>
<a href="howto_js_dropdown.asp">Click Dropdowns</a><br>
<a href="howto_css_table_responsive.asp">Responsive Tables</a><br>

HTML 포함

HTML 포함w3-include-html 속성 을 사용하여 수행 합니다.

    <div w3-include-html="content.html"></div>

JavaScript 추가

HTML 포함은 JavaScript로 수행됩니다.

    <script>
    function includeHTML() {
      var z, i, elmnt, file, xhttp;
      /*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("w3-include-html");
        if (file) {
          /*make an HTTP request using the attribute value as the file name:*/
          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("w3-include-html");
              includeHTML();
            }
          } 
          xhttp.open("GET", file, true);
          xhttp.send();
          /*exit the function:*/
          return;
        }
      }
    }
    </script>

페이지 하단에서 includeHTML ()을 호출합니다.

<!DOCTYPE html>
<html>
<script>
function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*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("w3-include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      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("w3-include-html");
          includeHTML();
        }
      }      
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
};
</script>
<body>

<div w3-include-html="h1.html"></div> 
<div w3-include-html="content.html"></div> 

<script>
includeHTML();
</script>

</body>
</html>

참고 URL : https://stackoverflow.com/questions/18712338/make-header-and-footer-files-to-be-included-in-multiple-html-pages

반응형