Is there an elegant way to use syntax highlighting on the "index.html" page?

On my index.html page, I have sections with code example, for which I want to use syntax highlighting. However, I cannot use the inbuild highlight function as it does not respect my render-codeblock.html hook, which is for Markdown only.

Nevertheless, I found a working solution by using $.Page.RenderString:

<div class="page">
   <div class="example">{{
`import org.tinylog.Logger;

public class Application {

    public static void main(String[] args) {
        Logger.info("Hello World!");
    }

}` | replaceRE `(?s)(.*)` "```java\n$1\n```" | $.Page.RenderString
   }}</div>
</div>

However, there are two major disadvantages:

  1. I found no way to escape backticks. Therefore, I use the replaceRE function for adding ```java to the start and ``` to the end.

  2. I cannot indent the code block itself as a whole. This makes my index.html page hard to read as there are many but tiny code examples.

You can use ~~~ instead of 3 backticks (see CommonMark specification).

<div class="page">
  <div class="example" style="margin-left: 2em">{{
`~~~java
import org.tinylog.Logger;

public class Application {

    public static void main(String[] args) {
        Logger.info("Hello World!");
    }

}
~~~` | $.Page.RenderString
  }}</div>
</div>

To indent the code block as a whole, add margin-left to div.example in your CSS.

Wouldn’t it be simpler to store the examples as page or global resources, then iterate to build the page?

3 Likes

Thank you, using ~~~ works well!

By indenting, I mean that I want to write my code indented:

<div class="page">
    <div class="example" style="margin-left: 2em">{{
        `~~~java
        import org.tinylog.Logger;
          
        public class Application {
          
            public static void main(String[] args) {
                Logger.info("Hello World!");
            }
          
        }
        ~~~` | $.Page.RenderString
    }}</div>
</div>

However, the rendered output should be without indentation:

import org.tinylog.Logger;
  
public class Application {
  
    public static void main(String[] args) {
        Logger.info("Hello World!");
    }
  
}

For me, it is simpler having the code blocks together with the explanation text on the same page, because I want usually edit both together.

Regarding indentation…

With four or more spaces, it will be rendered as an indented code block instead of a fenced code block.

See:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.