如何像Stack Overflow一样在我的网站上显示一段代码? [英] How to display a piece of code on my website like the way Stack Overflow does?
问题描述
我想安全地在我的网站上显示代码.我在前端使用Bootstrap,在服务器端使用PHP.
I want to securely display codes on my website. I am using Bootstrap on front end and PHP on server side.
我的网站上有一个注释框.
My site has a comment box.
如果我输入以下内容,则整个网页会失真.我想检测文本是否是代码,并像Stack Overflow一样以灰色背景显示它.因此,如果我使用代码标签,则开始标签保留在那里,但没有结束标签,最终导致我的网站失真.我也在尝试集成TinyMCE和CKEditor等文本编辑器.
If I enter something as following then the whole webpage gets distorted. I want to detect that the text is a code and display it with a greyish background just like Stack Overflow.I am creating a blog like website in which on the home page I am displaying first 300 characters. So if I use code tag then the opening tag remains there but there is no closing tag and I end up distorting my website. I am also trying to integrate text editors like TinyMCE and CKEditor.
<div class="text-muted">
推荐答案
您可以尝试使用 pre
和HTML实体,并应用一些CSS进行样式设置:
You can try the use of pre
and HTML entites and apply some CSS for styling:
pre {
border:1px solid #ccc;
padding:10px;
background:linear-gradient(#eff0f1,#eff0f1) 8px 8px/calc(100% - 16px) calc(100% - 16px) no-repeat;
}
<pre>
<a class="link"> this a link </a>
<p> this some content </p>
</pre>
然后,如果您想自动更改<
>
then you can consider some JS if you want to automatically change the <
>
let content = $('pre').html();
content = content.replace(/</g, '<');
content = content.replace(/>/g, '>');
$('pre').html(content);
pre {
border: 1px solid #ccc;
padding: 10px;
background: linear-gradient(#eff0f1, #eff0f1) 8px 8px/calc(100% - 16px) calc(100% - 16px) no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<pre>
<div class="container" data-attr="some data">
<img src="https://lorempixel.com/400/200/" >
<a class="link"> this a link </a>
<p> this some content </p>
</div>
</pre>
这些是非常简化的示例,您可以在网上找到许多可以应用高级样式的库:
These are very simplified examples and you can find on the net many library that allow you to apply advanced styling:
这篇关于如何像Stack Overflow一样在我的网站上显示一段代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!