如何在网页上显示非HTML代码

时间:2017-05-18 00:37:53

标签: html css

所以,目前,我有一些不必要的冗长代码来以编程格式显示文本。这就是我所拥有的:

    <table id = "code">
        <tr>
            <td id = "comment">/// If-statement example</td>
        </tr>
        <tr><td></td></tr>
        <tr>
            <td>var x = 5;</td>
        </tr>
        <tr><td></td></tr>
        <tr>
            <td>if x &#60 3</td>
        </tr>
        <tr>
            <td>{</td>
        <tr>
        <tr>
            <td>    draw_text(100, 100, "x is less than 3!");</td>
        </tr>
        <tr>
            <td>    // Above is a function to "draw" text to the screen.  It takes an x coordinate, a y coordinate, and text to draw.  If it's not in double quotes, then it will print the value of that variable.</td>
        </tr>
        <tr>
            <td>}</td>
        </tr>
    </table>

使用CSS:

#code
{
    text-align: left;
    font-family: "Times New Roman";
    font-size: 20px;
    position: float;
    margin: auto;
    margin-top: 10px;
    margin-bottom: 10px;
    width: 75%;
    border-style: solid;
    border-width: 1px;
    border-radius: 5px;
    border-color: #333;
}

#comment
{
    color: #91DD8D;
}

tr:nth-child(even)
{
    background: #444
}

tr:nth-child(odd)
{
    background: #666
}

table 
{
    counter-reset: rowNumber;
    font-size: 16px;
}

table tr 
{
    counter-increment: rowNumber;
    color: #DDD;
}

table tr td:first-child::before 
{
    content: counter(rowNumber);
    color: #DDD;
    min-width: 1em;
    margin-right: 0.5em;
}

生成的表格是具有交替背景颜色的表格,以及沿侧面打印的数字。但是,我希望看到更简单的方法来做到这一点;这是一个简单的十行代码,最终可能变成一个非常耗时的问题。感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

您可以尝试使用像php这样的转义代码来解析所有HTML。例如,您可以在后台使用php函数来收集每行代码的数组,例如:

<?php $array_of_code_lines = explode(PHP_EOL, $code_string_variable); ?>

然后你可以有一个简单的foreach循环以你想要的方式创建代码。

<table id = "code">
  <?php foreach($array_of_code_lines as $code_line) { ?>
    <tr>
      <td><?php echo $code_line; ?></td>
    </tr>
  <?php } ?>
</table>
相关问题