HTML로 HTML 코드 표시
각을 교체 할 필요없이 웹 페이지의 HTML 코드 조각을 보여줄 수있는 방법이 <
함께 <
와 >
함께는 >
?
즉, 닫는 태그를 칠 때까지 HTML을 렌더링하지 않는 태그가 있습니까?
아니요 , 없습니다. HTML에서 적절하게 일부 문자를 이스케이프 처리하는 방법은 없습니다.
&
같이&
<
같이<
(우연히도 피할 필요는 >
없지만 사람들은 종종 대칭 때문에 그것을 피합니다.)
물론 <pre><code>…</code></pre>
(a) 공백과 줄 바꿈을 유지하고 (b) 코드 요소로 표시하기 위해 이스케이프 처리 된 HTML 코드를 둘러싸 야합니다 .
코드를 <textarea>
(또는 더 이상 사용되지 않는) <xmp>
요소 로 포장하는 것과 같은 다른 모든 솔루션 은 중단 됩니다. 1
XML로 브라우저에 선언 XHTML (를 통해 HTTP Content-Type
헤더 - 단지가 설정! DOCTYPE
입니다 충분하지 ) 대안 CDATA 섹션을 사용할 수 있습니다 :
<![CDATA[Your <code> here]]>
그러나 이것은 HTML이 아닌 XML에서만 작동하며 코드에는 닫는 구분 기호가 없어야하기 때문에 완벽한 솔루션이 아닙니다 ]]>
. 따라서 XML에서도 가장 단순하고 강력한 솔루션은 이스케이프 처리입니다.
1 사례 :
textarea {border: none; width: 100%;}
<textarea readonly="readonly">
<p>Computer <textarea>says</textarea> <span>no.</span>
</textarea>
<xmp>
Computer <xmp>says</xmp> <span>no.</span>
</xmp>
HTML을위한 시도 된 진정한 방법 :
가장 좋은 방법은:
<xmp>
// your codes ..
</xmp>
오래된 샘플 :
샘플 1 :
<pre>
This text has
been formatted using
the HTML pre tag. The brower should
display all white space
as it was entered.
</pre>
샘플 2 :
<pre>
<code>
My pre-formatted code
here.
</code>
</pre>
샘플 3 : (실제로 코드 블록을 "인용"하는 경우 마크 업이됩니다)
<blockquote>
<pre>
<code>
My pre-formatted "quoted" code here.
</code>
</pre>
</blockquote>
멋진 CSS 샘플 :
pre{
font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
margin-bottom: 10px;
overflow: auto;
width: auto;
padding: 5px;
background-color: #eee;
width: 650px!ie7;
padding-bottom: 20px!ie7;
max-height: 600px;
}
구문 강조 코드 (프로 작업용) :
무지개 (매우 완벽)
당신을위한 최고의 링크 :
https://github.com/balupton/jquery-syntaxhighlighter
http://bavotasan.com/2009/how-to-wrap-text-within-the-pre-tag-using-css/
http://alexgorbatchev.com/SyntaxHighlighter/
https://code.google.com/p/jquery-chili-js/
코드를 표시하는 순진한 방법은 코드를 텍스트 영역에 포함하고 비활성화 된 속성을 추가하여 편집 할 수 없도록합니다.
<textarea disabled> code </textarea>
누군가가 일을 쉽게 할 수있는 방법을 찾는 데 도움이되기를 바랍니다 ..
더 이상 사용되지 않지만 FF3 및 IE8에서 작동합니다.
<xmp>
<b>bold</b><ul><li>list item</li></ul>
</xmp>
추천 :
<pre><code>
code here, escape it yourself.
</code></pre>
나는 <xmp>
이것을 다음과 같이 사용했다 : http://jsfiddle.net/barnameha/hF985/1/
HTML에서? 아니.
XML / XHTML에서? CDATA
블록을 사용할 수 있습니다 .
매우 간단합니다 ....이 xmp 코드를 사용하십시오
<xmp id="container">
<xmp >
<p>a paragraph</p>
</xmp >
</xmp>
더 이상 사용되지 않는 <xmp>
태그는 기본적으로 그렇게하지만 더 이상 XHTML 사양의 일부가 아닙니다. 현재 모든 브라우저에서 작동해야합니다.
다음은 또 다른 아이디어, 해킹 / 팔러 트릭입니다. 코드를 텍스트 영역에 넣을 수 있습니다.
<textarea disabled="true" style="border: none;background-color:white;">
<p>test</p>
</textarea>
텍스트 영역 안에 꺽쇠 괄호와 코드를 넣는 것은 유효하지 않은 HTML이며 다른 브라우저에서 정의되지 않은 동작을 일으킬 것입니다. Internet Explorer에서는 HTML이 해석되는 반면 Mozilla, Chrome 및 Safari는 해석되지 않습니다.
편집 불가능하고 다르게 보이기를 원한다면 CSS를 사용하여 쉽게 스타일을 지정할 수 있습니다. 유일한 문제는 브라우저가 오른쪽 하단 모서리에 작은 드래그 핸들을 추가하여 상자 크기를 조정한다는 것입니다. 또는 대신 입력 태그를 사용해보십시오.
텍스트 영역에 코드를 삽입하는 올바른 방법은 다음과 같은 PHP와 같은 서버 측 언어를 사용하는 것입니다.
<textarea disabled="true" style="border: none;background-color:white;">
<?php echo '<p>test</p>'; ?>
</textarea>
그런 다음 html 인터프리터를 무시하고 해석되지 않은 텍스트를 모든 브라우저에서 일관되게 텍스트 영역에 넣습니다.
그 이외의 유일한 방법은 정적 HTML 인 경우 코드를 직접 이스케이프하거나 그러한 기술을 사용하는 경우 .NET의 HtmlEncode ()와 같은 서버 측 메서드를 사용하는 것입니다.
나는 가정 :
- 100 % 유효한 HTML5를 작성하려고합니다
- 코드 스 니펫 (거의) 리터럴을 HTML에 배치하려고합니다.
- 특히
<
탈출 할 필요가 없습니다
- 특히
모든 옵션은이 트리에 있습니다.
- HTML 구문
- 5 가지 요소가 있습니다
- "정상 요소"(예
<p>
:)- 리터럴을 가질 수 없습니다
<
- 다음 태그 또는 주석의 시작으로 간주됩니다
- 리터럴을 가질 수 없습니다
- 공극 요소
- 그들은 내용이 없다
- HTML을 데이터 속성에 넣을 수는 있지만 모든 요소에 적용됩니다.
- 데이터를 다른 곳으로 옮기려면 JavaScript가 필요합니다
- 이중 인용 속성의
"
및&thing;
필요 탈출 :"
및&thing;
각각
- 원시 텍스트 요소
<script>
그리고<style>
오직- 그들은 결코 보이지 않습니다
- Javascript에 텍스트를 포함시키는 것이 가능할 수 있습니다.
- 자바 스크립트는 백틱이있는 여러 줄 문자열을 허용합니다
- 그런 다음 동적으로 삽입 할 수 있습니다
- 리터럴
</script
은 어디에서나 허용되지 않습니다<script>
- 탈출 가능한 원문 요소
<textarea>
그리고<title>
오직<textarea>
코드를 감쌀 수있는 좋은 후보입니다</html>
거기 에 쓰는 것은 완전히 합법적입니다</textarea
명백한 이유 때문에 합법적이지 않습니다.- 이 특별한 경우 탈출
</textarea
또는 유사한
- 이 특별한 경우 탈출
&thing;
탈출해야합니다 :&thing;
- 외국 요소
- MathML 및 SVG 네임 스페이스의 요소
- 적어도 SVG는 HTML을 다시 포함시킬 수 있습니다 ...
- CDATA가 허용되므로 잠재적 인 것으로 보입니다.
- XML 구문으로
- Konrad의 답변으로 덮여
참고 : >
이스케이프 할 필요가 없습니다. 정상적인 요소조차도 아닙니다.
동일한 페이지에서 다른 곳에서 실행중인 코드 덩어리를 보여주는 것이 목표라면 textContent를 사용할 수 있습니다 (순수하고 잘 지원됩니다 : http://caniuse.com/#feat=textcontent )
<div id="myCode">
<p>
hello world
</p>
</div>
<div id="loadHere"></div>
document.getElementById("myCode").textContent = document.getElementById("loadHere").innerHTML;
결과에서 여러 줄 형식을 얻으려면 CSS 스타일을 "white-space : pre;"로 설정해야합니다. 대상 div에 각 줄 끝에 "\ r \ n"을 사용하여 개별적으로 줄을 작성하십시오.
데모는 다음과 같습니다. https://jsfiddle.net/wphps3od/
이 방법은 텍스트 영역을 사용하는 것보다 이점이 있습니다. 코드는 텍스트 영역에서와 같이 다시 포맷되지 않습니다. (같은
것은 텍스트 영역에서 완전히 제거됩니다)
궁극적으로 가장 성가신 대답은 "텍스트 탈출"입니다.
그러나이 작업을 자동으로 수행 할 수있는 텍스트 편집기 나 독립형 미니 유틸리티가 많이 있습니다. 원하지 않는 경우 수동으로 이스케이프 처리하지 않아도됩니다 (이스케이프 처리 된 코드와 이스케이프 처리되지 않은 코드가 아닌 한 ...)
Quick Google search shows me this one, for example: http://malektips.com/zzee-text-utility-html-escape-regular-expression.html
You could use a server side language like PHP to insert raw text:
<?php
$str = <<<EOD
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Minimal HTML5">
<meta name="keywords" content="HTML5,Minimal">
<title>This is the title</title>
<link rel='stylesheet.css' href='style.css'>
</head>
<body>
</body>
</html>
EOD;
?>
then dump out the value of $str
htmlencoded:
<div style="white-space: pre">
<?php echo htmlentities($str); ?>
</div>
<textarea ><?php echo htmlentities($page_html); ?></textarea>
works fine for me..
"keeping in mind Alexander's
suggestion, here is why I think this is a good approach"
if we just try plain <textarea>
it may not always work since there may be closing textarea
tags which may wrongly close the parent tag and display rest of the HTML source on the parent document, which would look awkward.
using htmlentities
converts all applicable characters such as < >
to HTML entities which eliminates any possibility of leaks.
There maybe benefits or shortcomings to this approach or a better way of achieving the same results, if so please comment as I would love to learn from them :)
This is a simple trick and I have tried it in Safari and Firefox
<code>
<span><</span>meta property="og:title" content="A very fine cuisine" /><br>
<span><</span>meta property="og:image" content="http://www.example.com/image.png" />
</code>
It will show like this:
You can see it live Here
Actually there is a way to do this. It has limitation (one), but is 100% standard, not deprecated (like xmp), and works.
And it's trivial. Here it is:
<div id="mydoc-src" style="display: none;">
LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
<!--
YOUR CODE HERE.
<script src="WidgetsLib/all.js"></script>
^^ This is a text, no side effects trying to load it.
-->
LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
</div>
Please let me explain. First of all, ordinary HTML comment does the job, to prevent whole block be interpreted. You can easily add in it any tags, all of them will be ignored. Ignored from interpretation, but still available via innerHTML
! So what is left, is to get the contents, and filter the preceding and trailing comment tokens.
Except (remember - the limitation) you can't put there HTML comments inside, since (at least in my Chrome) nesting of them is not supported, and very first '-->' will end the show.
Well, it is a nasty little limitation, but in certain cases it's not a problem at all, if your text is free of HTML comments. And, it's easier to escape one construct, then a whole bunch of them.
Now, what is that weird LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo
string? It's a random string, like a hash, unlikely to be used in the block, and used for? Here's the context, why I have used it. In my case, I took the contents of one DIV, then processed it with Showdown markdown, and then the output assigned into another div. The idea was, to write markdown inline in the HTML file, and just open in a browser and it would transform on the load on-the-fly. So, in my case, <!--
became transformed to <p><!--</p>
, the comment properly escaped. It worked, but polluted the screen. So, to easily remove it with regex, the random string was used. Here's the code:
var converter = new showdown.Converter();
converter.setOption('simplifiedAutoLink', true);
converter.setOption('tables', true);
converter.setOption('tasklists', true);
var src = document.getElementById("mydoc-src");
var res = document.getElementById("mydoc-res");
res.innerHTML = converter.makeHtml(src.innerHTML)
.replace(/<p>.{0,10}LlNnlljn77fggggkk77csJJK8bbJBKJBkjjjjbbbJJLJLLJo.{0,10}<\/p>/g, "");
src.innerHTML = '';
And it works.
If somebody is interested, this article is written using this technique. Feel free to download, and look inside the HTML file.
It depends what you are using it for. Is it user input? Then use <textarea>
, and escape everything. In my case, and probably it's your case too, I simply used comments, and it does the job.
If you don't use markdown, and just want to get it as is from a tag, then it's even simpler:
<div id="mydoc-src" style="display: none;">
<!--
YOUR CODE HERE.
<script src="WidgetsLib/all.js"></script>
^^ This is a text, no side effects trying to load it.
-->
</div>
and JavaScript code to get it:
var src = document.getElementById("mydoc-src");
var YOUR_CODE = src.innerHTML.replace(/(<!--|-->)/g, "");
There are a few ways to escape everything in HTML, none of them nice.
Or you could put in an iframe
that loads a plain old text file.
This is by far the best method for most situations:
<pre><code>
code here, escape it yourself.
</code></pre>
I would have up voted the first person who suggested it but I don't have reputation. I felt compelled to say something though for the sake of people trying to find answers on the Internet.
This is how I did it:
$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";
function escapeHTML(string)
{
var pre = document.createElement('pre');
var text = document.createTextNode(string);
pre.appendChild(text);
return pre.innerHTML;
}//end escapeHTML
it will return the escaped Html
You could try:
Hello! Here is some code:
<xmp>
<div id="hello">
</div>
</xmp>
It may not work in every situation, but placing code snippets inside of a textarea
will display them as code.
You can style the textarea with CSS if you don't want it to look like an actual textarea.
//To show xml tags in table columns you will have to encode the tags first
function htmlEncode(value) {
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
html = htmlEncode(html)
By wrapping your code in a contenteditable
div and setting the white-space: pre-wrap;
indentation is preserved, code wraps accordingly to width and height is auto set:
<div class="code" contenteditable>
// code
</div>
.code {
white-space: pre-wrap;
}
참고URL : https://stackoverflow.com/questions/2820453/display-html-code-in-html
'IT story' 카테고리의 다른 글
전체 사이트에 대해 https를 강제 실행하는 asp.net의 가장 좋은 방법은 무엇입니까? (0) | 2020.05.18 |
---|---|
JavaScript에는 절전 기능이 있습니까? (0) | 2020.05.18 |
치명적인 오류 : 'SoapClient'클래스를 찾을 수 없습니다 (0) | 2020.05.18 |
다른 종속성을 건드리지 않고 단일 포드를 업데이트하는 방법 (0) | 2020.05.18 |
ASP.NET MVC 3 Razor-EditorFor에 클래스 추가 (0) | 2020.05.18 |