HTML 파일에 다른 HTML 파일 포함
파일이 2개 가정하면, 파일은 2개입니다.a.html
그리고.b.html
a.html
는 포하고싶다니습함을 하고 싶습니다.b.html
.
JSF에서는 다음과 같이 할 수 있습니다.
<ui:include src="b.xhtml" />
안에 있다는 입니다.a.xhtml
나는 일파, 포할수있다니를 할 수 .b.xhtml
.
우리가 어떻게 할 수 있습니까?*.html
파일?
제 생각에 최고의 솔루션은 jQuery를 사용합니다.
a.html
:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html
:
<p>This is my include file</p>
이 방법은 나의 문제에 대한 간단하고 깨끗한 해결책입니다.
jQuery.load()
설명서는 여기에 있습니다.
lolo의 대답을 확장하면, 만약 당신이 많은 파일을 포함해야 한다면, 여기에 조금 더 많은 자동화가 있습니다.다음 JS 코드 사용:
$(function () {
var includes = $('[data-include]')
$.each(includes, function () {
var file = 'views/' + $(this).data('include') + '.html'
$(this).load(file)
})
})
그런 다음 html에 무언가를 포함합니다.
<div data-include="header"></div>
<div data-include="footer"></div>
에는 파일 " 이포파된것다니입함그"가됩니다.views/header.html
그리고.views/footer.html
.
나의 해결책은 위의 lolo의 해결책과 비슷합니다.하지만 자바스크립트 문서를 통해 HTML 코드를 삽입합니다.jQuery를 사용하는 대신 쓰기:
a.sys:
<html>
<body>
<h1>Put your HTML content before insertion of b.js.</h1>
...
<script src="b.js"></script>
...
<p>And whatever content you want afterwards.</p>
</body>
</html>
b.js:
document.write('\
\
<h1>Add your HTML code here</h1>\
\
<p>Notice however, that you have to escape LF's with a '\', just like\
demonstrated in this code listing.\
</p>\
\
');
제가 jQuery.js를 사용하는 것을 반대하는 이유는 jQuery.js의 크기가 ~90kb이고, 로드할 데이터의 양을 가능한 한 작게 유지하고 싶기 때문입니다.
많은 작업 없이 적절하게 이스케이프된 JavaScript 파일을 가져오려면 다음 sed 명령을 사용할 수 있습니다.
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' b.html > escapedB.html
작업을 하여 Giston Github을 할 수 .b.html
b.js
: https://gist.github.com/Tafkadasoh/334881e18cbb7fc2a5c033bfa03f6ee6
원래의 sed 명령어가 고려하지 않은 백슬래시와 단일 따옴표도 이스케이프하는 개선된 sed 명령어에 대한 Greg Minshall의 크레딧.
템플릿 리터럴을 지원하는 브라우저의 경우 다음 기능도 작동합니다.
b.js:
document.write(`
<h1>Add your HTML code here</h1>
<p>Notice, you do not have to escape LF's with a '\',
like demonstrated in the above code listing.
</p>
`);
Html5rocks 튜토리얼 및 polymer-project를 통해 HTML5 가져오기 확인
예:
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
내가 이것을 해결하기 위해 쓴 도서관의 뻔뻔한 플러그.
https://github.com/LexmarkWeb/csi.js
<div data-include="/path/to/include.html"></div>
의 내용은 위의내다같습다니의 을 취할 입니다./path/to/include.html
그리고 그것을 대체합니다.div
그것과 함께.
스크립트가 필요 없습니다.서버 측면에서 화려한 작업을 수행할 필요가 없습니다(아마도 더 나은 옵션일 것입니다).
<iframe src="/path/to/file.html" seamless></iframe>
이전 브라우저는 원활하게 지원되지 않으므로 수정하려면 CSS를 몇 개 추가해야 합니다.
iframe[seamless] {
border: none;
}
원활하게 지원되지 않는 브라우저의 경우 iframe에서 링크를 클릭하면 프레임이 전체 창이 아닌 해당 URL로 이동합니다.이 문제를 해결하는 방법은 모든 링크가target="_parent"
브라우저 지원이 "충분히 좋습니다."
동일한 폴더에 있는 다른 파일을 포함하는 간단한 서버 측 포함 지시문은 다음과 같습니다.
<!--#include virtual="a.html" -->
또한 다음을 시도할 수 있습니다.
<!--#include file="a.html" -->
그 당시에는 제가 필요로 했던 아주 오래된 솔루션이었지만, 다음은 표준 준수 코드를 수행하는 방법입니다.
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="some.html">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="some.html">
<p>backup content</p>
</object>
<!--> <![endif]-->
인라인 솔루션은 다음과 같습니다.
(() => {
const includes = document.getElementsByTagName('include');
[].forEach.call(includes, i => {
let filePath = i.getAttribute('src');
fetch(filePath).then(file => {
file.text().then(content => {
i.insertAdjacentHTML('afterend', content);
i.remove();
});
});
});
})();
<p>FOO</p>
<include src="a.html">Loading...</include>
<p>BAR</p>
<include src="b.html">Loading...</include>
<p>TEE</p>
일부 파일의 HTML 콘텐츠를 포함해야 하는 경우 다음 작업이 수행됩니다.예를 들어, 다음 행에는 OBJECT 정의가 발생하는 위치에 piece_to_include.html의 내용이 포함됩니다.
...text before...
<OBJECT data="file_to_include.html">
Warning: file_to_include.html could not be included.
</OBJECT>
...text after...
참조: http://www.w3.org/TR/WD-html40-970708/struct/includes.html#h-7.7.4
w3.js에는 다음과 같은 작업이 포함됩니다.
<body>
<div w3-include-HTML="h1.html"></div>
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>
자세한 내용은 https://www.w3schools.com/howto/howto_html_include.asp 을 참조하십시오.
또는 서버의 .htaccess 파일에 액세스할 수 있는 경우 .html 확장자로 끝나는 파일에서 php를 해석할 수 있는 간단한 지시문을 추가할 수 있습니다.
RemoveHandler .html
AddType application/x-httpd-php .php .html
이제 간단한 php 스크립트를 사용하여 다음과 같은 다른 파일을 포함할 수 있습니다.
<?php include('b.html'); ?>
이것이 저를 도와준 것입니다.에서 b.html
a.html
이것은 안으로 들어가야 합니다.head
의 꼬리표.a.html
:
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
그런 다음 본체 태그에서 컨테이너는 고유 ID와 자바스크립트 블록으로 만들어져 로드됩니다.b.html
다음과 같이 용기에 넣습니다.
<div id="b-placeholder">
</div>
<script>
$(function(){
$("#b-placeholder").load("b.html");
});
</script>
저는 이것이 매우 오래된 게시물이라는 것을 알고 있습니다. 그래서 그 당시에는 몇몇 방법이 없었습니다.하지만 여기 그것에 대한 저의 매우 간단한 견해가 있습니다(롤로의 답변에 기초함).
HTML5 data-* 속성에 의존하므로 jQuery의 for-each 함수를 사용하여 모든 .class 일치 "load-html"을 가져오고 각각의 'data-source' 속성을 사용하여 콘텐츠를 로드한다는 점에서 매우 일반적입니다.
<div class="container-fluid">
<div class="load-html" id="NavigationMenu" data-source="header.html"></div>
<div class="load-html" id="MainBody" data-source="body.html"></div>
<div class="load-html" id="Footer" data-source="footer.html"></div>
</div>
<script src="js/jquery.min.js"></script>
<script>
$(function () {
$(".load-html").each(function () {
$(this).load(this.dataset.source);
});
});
</script>
대부분의 솔루션은 작동하지만 jquery에는 문제가 있습니다.
다음 코드에 따라 문제가 발생합니다.$(document).ready(function () { alert($("#includedContent").text()); }
는 포함된 내용을 경고하는 대신 아무것도 경고하지 않습니다.
코드를 하며, 제 은 래코를작다니성합아드다있수포에 할 수 .$(document).ready
함수:
(중요한 것은 포함된 컨텐츠를 동기적으로 로드하는 것입니다.)
index.htm:
<html>
<head>
<script src="jquery.js"></script>
<script>
(function ($) {
$.include = function (url) {
$.ajax({
url: url,
async: false,
success: function (result) {
document.write(result);
}
});
};
}(jQuery));
</script>
<script>
$(document).ready(function () {
alert($("#test").text());
});
</script>
</head>
<body>
<script>$.include("include.inc");</script>
</body>
</html>
포함합니다.inc:
<div id="test">
There is no issue between this solution and jquery.
</div>
HTML Imports(https://www.html5rocks.com/en/tutorials/webcomponents/imports/), 또는 단순화된 솔루션 https://github.com/dsheiko/html-import )의 폴리필을 사용할 수 있습니다.
예를 들어 페이지에서 다음과 같이 HTML 블록을 가져옵니다.
<link rel="html-import" href="./some-path/block.html" >
블록에 자체 가져오기가 있을 수 있습니다.
<link rel="html-import" href="./some-other-path/other-block.html" >
가져오기 기능은 SSI와 거의 유사하게 로드된 HTML로 지침을 대체합니다.
이 작은 JavaScript를 로드하는 즉시 다음 지침이 자동으로 제공됩니다.
<script async src="./src/html-import.js"></script>
DOM이 자동으로 준비되면 가져오기를 처리합니다.또한 수동으로 실행하거나 로그를 가져오는 등에 사용할 수 있는 API를 제공합니다.즐기세요 :)
Fetch API 및 비동기 기능을 사용하는 제 접근 방식은 다음과 같습니다.
<div class="js-component" data-name="header" data-ext="html"></div>
<div class="js-component" data-name="footer" data-ext="html"></div>
<script>
const components = document.querySelectorAll('.js-component')
const loadComponent = async c => {
const { name, ext } = c.dataset
const response = await fetch(`${name}.${ext}`)
const html = await response.text()
c.innerHTML = html
}
[...components].forEach(loadComponent)
</script>
명명된 파일의 내용을 삽입하는 방법
<!--#include virtual="filename.htm"-->
Fetch API with Promise를 사용하는 다른 접근법
<html>
<body>
<div class="root" data-content="partial.html">
<script>
const root = document.querySelector('.root')
const link = root.dataset.content;
fetch(link)
.then(function (response) {
return response.text();
})
.then(function (html) {
root.innerHTML = html;
});
</script>
</body>
</html>
아이프레임 주사는 시도해 보셨습니까?
문서에 iFrame을 주입하고 자체 삭제합니다(HTML DOM에 있어야 함).
<iframe src="header.html" onload="this.before((this.contentDocument.body||this.contentDocument).children[0]);this.remove()"></iframe>
안부 전해요
아타리의 대답(첫 번째!)은 너무 결정적이었습니다!아주 좋아요!
그러나 URL 매개 변수로 포함할 페이지의 이름을 전달하고 싶다면, 이 게시물에는 다음과 함께 사용할 수 있는 매우 좋은 솔루션이 있습니다.
http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
그래서 다음과 같이 됩니다.
사용자의 URL:
www.yoursite.com/a.html?p=b.html
이제 a.html 코드는 다음과 같습니다.
<html>
<head>
<script src="jquery.js"></script>
<script>
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
$(function(){
var pinc = GetURLParameter('p');
$("#includedContent").load(pinc);
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
그것은 저에게 매우 잘 작동했습니다!도움이 되었기를 바랍니다 :)
html5rocks.com 은 이런 것들에 대한 아주 좋은 튜토리얼을 가지고 있고, 이것은 조금 늦을 수도 있지만, 저 자신은 이것이 존재하는지 몰랐습니다. 또한 w3.js라고 불리는 그들의 새로운 라이브러리를 사용하여 이것을 할 수 있는 방법을 가지고 있습니다.중요한 것은, 이를 위해서는 웹 서버와 HTTP 요청 개체를 사용해야 한다는 것입니다.실제로 로컬로 로드하여 컴퓨터에서 테스트할 수 없습니다.하지만 당신이 할 수 있는 것은 상단의 html5rocks 링크에 제공된 폴리필을 사용하거나 튜토리얼을 따르는 것입니다.작은 JS 마법으로 다음과 같은 작업을 수행할 수 있습니다.
var link = document.createElement('link');
if('import' in link){
//Run import code
link.setAttribute('rel','import');
link.setAttribute('href',importPath);
document.getElementsByTagName('head')[0].appendChild(link);
//Create a phantom element to append the import document text to
link = document.querySelector('link[rel="import"]');
var docText = document.createElement('div');
docText.innerHTML = link.import;
element.appendChild(docText.cloneNode(true));
} else {
//Imports aren't supported, so call polyfill
importPolyfill(importPath);
}
이렇게 하면 링크가 생성되고(이미 설정된 경우 원하는 링크 요소로 변경할 수 있음) 가져오기를 설정한 다음(이미 설정하지 않은 경우) 추가합니다.그런 다음 그것을 가져와서 HTML로 파일을 구문 분석한 다음 div 아래의 원하는 요소에 추가합니다.이 모든 것은 추가 요소에서 사용 중인 링크에 이르기까지 사용자의 필요에 맞게 변경될 수 있습니다.저는 이것이 도움이 되었기를 바랍니다, 만약 jQuery나 W3.js와 같은 라이브러리와 프레임워크를 사용하지 않고 더 새롭고 빠른 방법이 나온다면 지금은 상관이 없을 수도 있습니다.
업데이트: 로컬 가져오기가 CORS 정책에 의해 차단되었다는 오류가 발생합니다.Deep Web의 특성 때문에 이를 사용하려면 Deep Web에 대한 액세스가 필요할 수 있습니다. (실용적인 사용이 없음을 의미)
다음을 포함HTML(가장 작은 js-lib: ~150줄)
HTML 태그를 통해 HTML 부품 로드(순수 js)
지원되는 로드: 비동기/동기화, 모든 심층 재귀 포함
지원되는 프로토콜: http://, https://, file:///
지원되는 브라우저: IE 9+, FF, Chrome(기타 브라우저일 수 있음)
용도:
1. HTML 파일의 헤드 섹션(또는 본문 닫기 태그 앞)에 includeHTML을 삽입합니다.
<script src="js/includeHTML.js"></script>
2.어디서나 HTML을 HTML 태그로 사용:
<div data-src="header.html"></div>
이 솔루션들 중 어느 것도 제 요구에 맞지 않습니다.저는 좀 더 PHP 같은 것을 찾고 있었습니다.제 생각에 이 해결책은 꽤 쉽고 효율적입니다.
include.js
->
void function(script) {
const { searchParams } = new URL(script.src);
fetch(searchParams.get('src')).then(r => r.text()).then(content => {
script.outerHTML = content;
});
}(document.currentScript);
index.html
->
<script src="/include.js?src=/header.html">
<main>
Hello World!
</main>
<script src="/include.js?src=/footer.html">
간단한 수정을 통해 생성할 수 있습니다.include_once
,require
,그리고.require_once
당신이 하는 일에 따라 유용할 수도 있습니다.여기 그것이 어떻게 보일지에 대한 간단한 예가 있습니다.
include_once
->
var includedCache = includedCache || new Set();
void function(script) {
const { searchParams } = new URL(script.src);
const filePath = searchParams.get('src');
if (!includedCache.has(filePath)) {
fetch(filePath).then(r => r.text()).then(content => {
includedCache.add(filePath);
script.outerHTML = content;
});
}
}(document.currentScript);
도움이 되길 바랍니다!
현재 작업에 대한 직접적인 HTML 솔루션은 없습니다.Import!= Include 및 일부 JS Magic이 필요하기 때문에 HTML Imports(영구 초안에 있는 HTML Imports)도 이 작업을 수행하지 않습니다.
나는 최근에 바닐라를 썼습니다.HTML을 HTML에 포함시키기 위한 JS 스크립트입니다.
당신의 안에 그냥 배치하세요.a.html
<link data-wi-src="b.html" />
<!-- ... and somewhere below is ref to the script ... -->
<script src="wm-html-include.js"> </script>
그렇다.open-source
그리고 아이디어를 줄 수도 있습니다 (나는 희망합니다)
다음과 같은 JavaScript 라이브러리 jQuery를 사용하여 이 작업을 수행할 수 있습니다.
HTML:
<div class="banner" title="banner.html"></div>
JS:
$(".banner").each(function(){
var inc=$(this);
$.get(inc.attr("title"), function(data){
inc.replaceWith(data);
});
});
참고로banner.html
당신의 다른 페이지가 있는 같은 도메인 아래에 위치해야 합니다. 그렇지 않으면 당신의 웹 페이지는 거부할 것입니다.banner.html
교차 오리진 리소스 공유 정책으로 인해 파일이 생성되었습니다.
또한 자바스크립트로 콘텐츠를 로드하면 구글이 인덱스를 작성할 수 없기 때문에 SEO에 적합한 방법이 아니라는 점에 유의하시기 바랍니다.
웹 구성요소
JSF와 유사한 다음 웹 구성 요소를 만듭니다.
<ui-include src="b.xhtml"><ui-include>
(스니펫 js 코드를 포함한 후) 페이지 내에서 일반 html 태그로 사용할 수 있습니다.
customElements.define('ui-include', class extends HTMLElement {
async connectedCallback() {
let src = this.getAttribute('src');
this.innerHTML = await (await fetch(src)).text();;
}
})
ui-include { margin: 20px } /* example CSS */
<ui-include src="https://cors-anywhere.herokuapp.com/https://example.com/index.html"></ui-include>
<div>My page data... - in this snippet styles overlaps...</div>
<ui-include src="https://cors-anywhere.herokuapp.com/https://www.w3.org/index.html"></ui-include>
여기 좋은 기사가 있습니다. 공통 라이브러리를 구현하고 아래 코드를 사용하여 HTML 파일을 한 줄로 가져올 수 있습니다.
<head>
<link rel="import" href="warnings.html">
</head>
Google Polymer를 사용해 볼 수도 있습니다.
솔루션을 작동시키려면 여기에서 찾을 수 있는 csi.min.js 파일을 포함해야 합니다.
GitHub에 표시된 예제와 같이 이 라이브러리를 사용하려면 페이지 헤더에 csi.js 파일을 포함해야 합니다. 그런 다음 값이 설정된 data-include 특성을 컨테이너 요소에 포함할 파일에 추가해야 합니다.
복사 코드 숨기기
<html>
<head>
<script src="csi.js"></script>
</head>
<body>
<div data-include="Test.html"></div>
</body>
</html>
도움이 되길 바랍니다.
여기에는 몇 가지 유형의 답변이 있지만, 여기에서 사용되는 가장 오래된 도구를 찾을 수 없습니다.
"그리고 다른 모든 대답들은 저에게 효과가 없었습니다."
<html>
<head>
<title>pagetitle</title>
</head>
<frameset rows="*" framespacing="0" border="0" frameborder="no" frameborder="0">
<frame name="includeName" src="yourfileinclude.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0">
</frameset>
</html>
언급URL : https://stackoverflow.com/questions/8988855/include-another-html-file-in-a-html-file
'source' 카테고리의 다른 글
전체 입력 문자열을 변환하기 전에 Oracle 날짜 형식 그림이 종료됩니다. (0) | 2023.07.08 |
---|---|
'gitrebase'를 사용하여 이전 커밋 메시지 변경 (0) | 2023.07.08 |
함수를 호출할 때 매개 변수의 이름을 강제로 지정하려면 어떻게 해야 합니까? (0) | 2023.07.08 |
빈 JavaScript 개체를 테스트하려면 어떻게 해야 합니까? (0) | 2023.07.08 |
MongoDB에서 초기 데이터를 로드하는 방법은 무엇입니까? (0) | 2023.07.08 |