Pug - including c code with "include" keyword in it

Viewed 54

I want to put c file content in html document with pug. For that I use:

<pre>
        <code>
            include main.c
        </code>
</pre>

In my main.c file I have:

#include <stdio.h>
#include <stdlib.h>

It then compiles to:

<pre>
<code>
 "#include "
 <stdio.h>
  "#include "
  <stdlib.h>
   ...
  </stdlib.h>
 </stdio.h>
</code>
</pre>

How can I prevent that and have <stdio.h> included as normal text ? PS: works fine with (#include "main.h", not using <>)

2 Answers

The <> are special reserved HTML chars. This chars must be escaped. In Pug, you can use filters for this.

If you use Webpack to compile Pug files in static HTML, then you can use the @webdiscus/pug-loader. This pug-loader has embedded filters such :escape, :highlight, :markdown that do exact what you need.

Usage the :escape Pug filter applied to included main.c:

pre: code
  include:escape main.c

Generated HTML:

<pre>
  <code>
    #include &lt;stdio.h&gt;
    #include &lt;stdlib.h&gt;
  </code>
</pre>

Output in browser:

#include <stdio.h>
#include <stdlib.h>

If you're using pug, you're probably using a UI framework like Vue? If so, just turn your file code into a variable and place it this way (i.e. <code>{{myCode}}</code>. Pug isn't meant for processing hard-coded code like you're doing it (entering it directly or including it from a file). If you do that you'll have to keep escaping it and other shenanigans.

If you push it back to a variable, you'll see more options logically open up to what is possible for you.

Also, the way you're doing it, the C file has to be available to pug at the file level, to the pug renderer, which is doing yourself a disservice as you can only render it server side.

If you push it to a variable you can render it client-side, or from anywhere at any point.

Related