Keto Z
Keto Z

Reputation: 41

How to display non-HTML code on a webpage

So, at the moment, I have some unnecessarily lengthy code to display text in a programming format. Here's what I've got:

    <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>

With the CSS of:

#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;
}

The resulting table is one with alternating background colors, as well as numbers printed along the side. However, I'm looking to see an easier way to do this; it's a simple ten lines of code, and could eventually turn into an extremely time-consuming issue. Any help is appreciated, thank you!

Upvotes: 0

Views: 115

Answers (1)

Jake Killpack
Jake Killpack

Reputation: 107

You could try using escaped code like php to parse all the HTML for you. For example, you could have a php function in the background that collected an array of each line of code such as:

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

and then you could have a simple foreach loop create the code in the way that you want.

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

Upvotes: 1

Related Questions