Thursday, 25 July 2019

Using Prism in Blogger for code highlighting

JavaScript  Prism 

Prism is a lightweight syntax highlighter in javascript. It is easy to use, fast and extensible. It supports 184 languages and is used on some popular websites such as Drupal, React and Stripe.

How to setup Prism in Blogger platform?

It is very easy to setup Prism on Blogger platform. After logging in to Blogger, click Theme on the left-side menu. Then click the button Edit HTML under the selected blog theme. It opens the HTML source code of the selected blog theme page. Copy and paste the following HTML code before the HTML tag </head>.

<link href='https://cdn.jsdelivr.net/npm/prismjs@1.17.1/themes/prism.css' rel='stylesheet'/>
<link href='https://cdn.jsdelivr.net/npm/prismjs@1.17.1/plugins/line-numbers/prism-line-numbers.css' rel='stylesheet'/>
<script src='https://cdn.jsdelivr.net/npm/prismjs@1.17.1/components/prism-core.min.js' type='text/javascript'/>
<script src='https://cdn.jsdelivr.net/npm/prismjs@1.17.1/plugins/autoloader/prism-autoloader.min.js' type='text/javascript'/>
<script src='https://cdn.jsdelivr.net/npm/prismjs@1.17.1/plugins/line-numbers/prism-line-numbers.min.js' type='text/javascript'/>

Files of Prism are hosted in CDN (Content Delivery Network): jsdelivr. Line 1 in the code snippet above is the CSS file for the default theme of Prism, Line 2 is the CSS file for the Line numbers plugin, Line 3 is the core javascript file of Prism, Line 4 is the javascript file that automatically loads languages when necessary, and Line 5 is the plugin javascript file for showing line numbers in the code snippet. That's it! The setting up process is so simple.


How to use?

For a code block, we use <pre> and <code> tags as below. In Line 1, we add a class line-numbers to request Prism to print out the line numbers for the code block. In Line 2, the class language-php is for getting the PHP for the code block. For other languages, you can use the pattern language-xxxx and replace the xxxx with the language code that supported by Prism.

<pre class="line-numbers">
<code class="language-php">
$str = "Hello world!";
echo $str;
</code>
</pre>

Then, the above code snippet (Line 3 and Line 4) is highlighted by Prism as below.

$str = "Hello world!";
echo $str;

For an inline code, we can just use a <code> tag. For example, we can highlight a java code inline like this:

<code class="language-java">int myNum = 50;</code>

The inline code is highlighted as: int myNum = 50;

For more examples and supported languages of Prism, you can refer to its website: https://prismjs.com



Search