prismjs 是一款輕量、可擴展的代碼語法高亮庫,使用現代化的 Web 標準構建,使用 Prismjs 可以快速為網站添加代碼高亮功能,支持超過113中編程語言,還支持多種插件,是簡潔、高效的代碼高亮解決方案。科技愛好者博客就是使用了Prism.js 實現漂亮的代碼語法高亮功能,本文教你如何在wordpress上快速使用Prismjs實現代碼高亮。
一、下載JS和CSS文件並上傳到網站根目錄。
在Prismjs網站下載頁面下載需要的JS和CSS文件,下載頁面:
在下載頁面,需要選擇高亮模板、支持的編程語言、插件,選擇完畢後下載生成的JS和CSS文件。
二、上傳JS和CSS文件到網站模板目錄
注:(以Wordpress為例)我把文件上傳到了網站的wp-content目錄,然後在頁面中引用。
三、修改header.php和footer.php文件
找到wordpress 使用的主題目錄,分別修改header.php和footer.php文件
打開header.php文件,在標籤前添加CSS引用。修改後就是這樣
<html>
<head>
...
<link href="themes/prism.css" rel="stylesheet" />
</head>
打開footer.php文件,在標籤前添加JS引用,修改後如下:
<body>
...
<script src="prism.js"></script>
</body>
四、在文章中引用
完成上述步驟後,就可以在wordpress文章中引用了。
在發表文章時將代碼塊用<code><pre>標籤包圍起來,就可以實現代碼高亮功能了!
例1如下:
<pre><code class="language-php">
<?php
echo "Hello World!";
?>
</code>
</pre>
例2如下:
``` csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace inTestCar.Web
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
```
五、代碼塊添加行號
在<pre>裏添加 line-numbers 類就可以開啓代碼快的行號,當然前提是你必須下載Line Numbers插件。添加方式如下:
<pre class="line-numbers"><code class="language-css">
或
``` css
代碼
```
六、prismjs支持的語言
Markup - markup
CSS - css
C-like - clike
JavaScript - javascript
ABAP - abap
ActionScript - actionscript
Apache Configuration - apacheconf
APL - apl
AppleScript - applescript
AsciiDoc - asciidoc
ASP.NET (C#) - aspnet
AutoIt - autoit
AutoHotkey - autohotkey
Bash - bash
BASIC - basic
Batch - batch
Bison - bison
Brainfuck - brainfuck
Bro - bro
C - c
C# - csharp
C++ - cpp
CoffeeScript - coffeescript
Crystal - crystal
CSS Extras - css-extras
D - d
Dart - dart
Diff - diff
Docker - docker
Eiffel - eiffel
Elixir - elixir
Erlang - erlang
F# - fsharp
Fortran - fortran
Gherkin - gherkin
Git - git
GLSL - glsl
Go - go
Groovy - groovy
Haml - haml
Handlebars - handlebars
Haskell - haskell
Haxe - haxe
HTTP - http
Icon - icon
Inform 7 - inform7
Ini - ini
J - j
Jade - jade
Java - java
JSON - json
Julia - julia
Keyman - keyman
Kotlin - kotlin
LaTeX - latex
Less - less
LOLCODE - lolcode
Lua - lua
Makefile - makefile
Markdown - markdown
MATLAB - matlab
MEL - mel
Mizar - mizar
Monkey - monkey
NASM - nasm
nginx - nginx
Nim - nim
Nix - nix
NSIS - nsis
Objective-C - objectivec
OCaml - ocaml
Oz - oz
PARI/GP - parigp
Parser - parser
Pascal - pascal
Perl - perl
PHP - php
PHP Extras - php-extras
PowerShell - powershell
Processing - processing
Prolog - prolog
Protocol Buffers - protobuf
Puppet - puppet
Pure - pure
Python - python
Q - q
Qore - qore
R - r
React JSX - jsx
reST (reStructuredText) - rest
Rip - rip
Roboconf - roboconf
Ruby - ruby
Rust - rust
SAS - sas
Sass (Sass) - sass
Sass (Scss) - scss
Scala - scala
Scheme - scheme
Smalltalk - smalltalk
Smarty - smarty
SQL - sql
Stylus - stylus
Swift - swift
Tcl - tcl
Textile - textile
Twig - twig
TypeScript - typescript
Verilog - verilog
VHDL - vhdl
vim - vim
Wiki markup - wiki
YAML - yaml