Post

Embedding PrismJS into Vaadin 24

Embedding PrismJS into Vaadin 24

PrismJS is a lightweight and extensible syntax highlighter that is widely used to highlight code snippets in web applications. If you’re developing a Vaadin application and want to embed PrismJS to highlight your code blocks, you’re in the right place! In this blog post, we will walk through the process of embedding PrismJS into a Vaadin project. You’ll learn how to add the necessary dependencies and execute the required JavaScript to ensure your code is highlighted effectively on the frontend.


📚 What is PrismJS?

PrismJS is an open-source library that allows developers to easily highlight code in web pages. It supports a wide variety of programming languages and is known for being fast, lightweight, and easy to integrate. The library offers syntax highlighting for numerous languages like JavaScript, Python, Ruby, and more, making it an ideal choice for displaying code in an aesthetically pleasing way.


🛠️ Setting Up PrismJS in Vaadin

In order to embed PrismJS in a Vaadin project, we need to follow a few simple steps. These steps involve adding PrismJS’s JavaScript and CSS to your project and running the necessary JavaScript commands after the components are rendered. Let’s break it down:


🗂️ Step 1: Download PrismJS with Language Support and Plugins

To get started, you’ll need to download PrismJS with the appropriate language support and plugins. By default, PrismJS only includes a basic JavaScript syntax highlighter. If you want to add syntax support for other programming languages (like Java, Python, HTML, etc.), you’ll need to include additional language definitions and plugins.

  1. Go to the PrismJS download page:
    Visit PrismJS Download Page.

  2. Choose the languages and plugins you need:
    • Languages: Select the languages you need, such as JavaScript, Java, Python, HTML, etc.
    • Plugins: Choose any plugins you may need, such as the Line Numbers, Autoloader, or Toolbar plugin, depending on the features you want to add.
  3. Download the package:
    Once you’ve selected the appropriate languages and plugins, click the “Download” button to download a .zip file containing all the required files.

  4. Extract the files:
    After downloading, extract the contents of the .zip file. Inside, you’ll find JavaScript and CSS files for PrismJS, along with individual language files and any plugin scripts you selected.

  5. Place the files in your project:
    Copy the extracted files into your Vaadin project. Place the JavaScript and CSS files in the appropriate directories within your frontend folder, for example:
    • /src/main/frontend/js/prism.js
    • /src/main/frontend/css/prism.css

🔌 Step 2: Add the PrismJS Dependencies

The next step is to import the PrismJS JavaScript and CSS files into your Vaadin component. To do this, use the @JavaScript and @CssImport annotations provided by Vaadin. This will make the PrismJS library available in your Vaadin component.

1
2
@JavaScript("/js/prism.js")
@CssImport("/css/prism.css")

This code snippet imports both the PrismJS JavaScript file and the accompanying CSS file into your component. You’ll want to ensure that the paths to prism.js and prism.css are correct, and the files are placed within the frontend folder of your project.


🚀 Step 3: Highlight Code After Changes Are Sent to the Frontend

Once the JavaScript and CSS files are successfully imported, we need to run the PrismJS.highlightAll() method to ensure the code is highlighted after the changes have been sent to the frontend.

The key here is that this JavaScript code should not run in the constructor of your component, as the component may not yet be rendered on the client-side. Instead, we need to execute the JavaScript after the UI is ready.

Here’s how you can execute the JavaScript to highlight all the code blocks:

1
getUI().ifPresent(ui -> ui.getPage().executeJs("Prism.highlightAll();"));

This ensures that after the component is rendered, all the code blocks in your application will be highlighted.


💻 Full Example

Here’s an example of how to use PrismJS within a Vaadin component. The following code will render a component with some syntax-highlighted code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Route("highlighted-code")
@JavaScript("/js/prism.js")
@CssImport("/css/prism.css")
public class HighlightedCodeView extends VerticalLayout {

    public HighlightedCodeView() {
        // Create a simple code block
        String codeSnippet = "public class HelloWorld { \n" +
                             "  public static void main(String[] args) { \n" +
                             "    System.out.println(\"Hello, world!\"); \n" +
                             "  } \n" +
                             "}";

        // Create a preformatted text element to hold the code
        Span codeElement = new Span();
        codeElement.getElement().setProperty("innerHTML", "<pre><code class='language-java'>" + codeSnippet + "</code></pre>");
        
        // Add the code element to the layout
        add(codeElement);        
    }

    @Override
    protected void onAttach(AttachEvent attachEvent) {
        super.onAttach(attachEvent);

        // Ensure syntax highlighting happens after UI is rendered
        getUI().ifPresent(ui -> ui.getPage().executeJs("Prism.highlightAll();"));
    }
}

In this example:

  • We use @JavaScript and @CssImport to import PrismJS’s JavaScript and CSS.
  • A simple Java code snippet is added within a Span element as preformatted text.
  • After adding the code block, we call Prism.highlightAll() to trigger the syntax highlighting.

🧠 Final Thoughts

Integrating PrismJS into Vaadin is a simple and effective way to enhance the appearance of code snippets in your web applications. By following the two key steps outlined—adding the JavaScript and CSS imports, and executing the highlightAll() method after rendering—you can easily showcase highlighted code in your Vaadin app.

Happy coding, and I hope this tutorial helps you make your Vaadin projects even more engaging!

This post is licensed under CC BY 4.0 by the author.