受欢迎的博客标签

How to add code snippets using TinyMCE and Prism.js?(tinymce+prism实现代码高亮)

Published

TinyMCE  v5

tinymce_5.1.6

How to add a snippet

Include the TinyMCE script-Include the following line of code in the <head> of a HTML page

<script type="text/javascript" src="~/lib/tinymce_5.1.6/js/tinymce/tinymce.min.js"></script>

 

To add code snippets to your content, you can use the codesample plugin (usually included in the community version). To enable this plugin, you only need to provide the name of the plugin "codesample" in the plugins property of the initialization object and add the action button in the toolbar, identified with the same name "codesample":

 

tinymce.init({
    selector: 'textarea',   // change this value according to your HTML
    plugins: 'codesample',
    toolbar: 'codesample'
});

Once you add the codesample plugin and the action button in the toolbat, your tinymce should show the new button.

How to add a list of languages to be displayed in the languages drop down

The language is defined through the way recommended in the HTML5 draft: through a language-xxxx class. With TinyMCE, this language can be set through a select element shown in the code input dialog. You can add new languages at the initialization by setting the codesample_languages property:

tinymce.init({
    selector: 'textarea',
    plugins: 'codesample',      
    codesample_languages: [                              //This configuration option enables you to set a list of languages to be displayed in the languages drop down.
        {text: 'HTML/XML', value: 'markup'},
        {text: 'JavaScript', value: 'javascript'},
        {text: 'CSS', value: 'css'},
        {text: 'PHP', value: 'php'},
        {text: 'Ruby', value: 'ruby'},
        {text: 'Python', value: 'python'},
        {text: 'Java', value: 'java'},
        {text: 'C', value: 'c'},
        {text: 'C#', value: 'csharp'},
        {text: 'C++', value: 'cpp'}
    ],
    toolbar: 'codesample'
});

Now if you click on the codesample button in TinyMCE, then you should see the code input dialog.

 

All unsafe characters for the generated HTML (like a HTML snippet inside) will be automatically escaped to its html symbol, so the HTML generated by TinyMCE with a html snippet should look like:

<p>Span tag in HTML:</p>
<pre class="language-html"><code>&lt;span&gt;Hello World&lt;/span&gt;</code></pre>
<p>Hello World !</p>

 

This plugin can be used from the version 4.3 of TinyMCE. Therefore it was in "test stage" and there were several bugs and modifications, however most of them were quickly solved e.g you couldn't load more than 10 languages to highlight.

 

Prism

You need to add prism.js and prism.css to your page in order to get the syntax highlighted code samples on your webpage (as created by the Code Sample plugin).

<link href="prism.css" rel="stylesheet" />
<script src="prism.js"></script>

Prism forces you to use the correct element for marking up code: <code>. On its own for inline code, or inside a <pre> for blocks of code.

By default TinyMCE uses the default theme of Prism included by default in the plugin.

 

 the list of all 260 languages currently supported by Prism

 

https://prismjs.com/

 

 

 Prism style

 

 

TinyMCE  v4.3

一、编辑页配置

1.首先我们需要引用网页样式控制文件及脚本语言编辑文件(其中前两个是tinymce脚本文件,后两个是prism高亮文件)

 

<script type="text/javascript" src="tinymce.min.js"></script>
<script type="text/javascript" src="jquery.tinymce.min.js"></script>
<link href="prism.css" rel="stylesheet" />
<script src="prism.js"></script>

2.在body中设计好我们的文本

<textarea name="content" style="width:100%"></textarea>

3.在js中进行文本的初始化

(1)tinymce.init配置并初始化tinymce

(2)selector: "textarea"根据你的选择器来指定,我这里是textarea,可以绑定id(#···)或class(.····)

(3)plugins填写要使用的插件名称

(4)toolbar设置工具栏指定显示插件,这里我展示了三个工具栏

(5)menubar禁用菜单栏模板

(6)toolbar_items_size工具栏标签大小设置为小

(7)style_formats初始化的默认样式,这个根据自己喜好调节

(8)templates模板,toolbar3中的template选中标题后自动追加值content到文本框

(9)language:'zh_CN'语言本身默认英文,这里指定语言为中文

<script type="text/javascript">
    tinymce.init({
        selector: "textarea",
        plugins: [
            "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
            "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
            "table contextmenu directionality emoticons template textcolor paste fullpage textcolor codesample"
        ],
 
        toolbar1: "undo redo | cut copy paste | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",
        toolbar2: " searchreplace | bullist numlist | outdent indent blockquote | link unlink anchor image media code codesample | inserttime preview | forecolor backcolor",
        toolbar3: "table | hr removeformat | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft",
 
        menubar: false,
        toolbar_items_size: 'small',
 
        style_formats: [
            {title: 'Bold text', inline: 'b'},
            {title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
            {title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
            {title: 'Example 1', inline: 'span', classes: 'example1'},
            {title: 'Example 2', inline: 'span', classes: 'example2'},
            {title: 'Table styles'},
            {title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
        ],
 
        templates: [
            {title: 'Test template 1', content: 'Test 1'},
            {title: 'Test template 2', content: 'Test 2'}
        ],
        language:'zh_CN'
    });</script>

 

添加codesample插件,将会产生

class=“language-**”标签,这个一眼看去和prism高亮显示插件是迎合的。所以我们使用prism作为代码高亮插件。

Custom languages list

we provide you the list of all supported languages by Prism.js to use in the codesample_languages property of TinyMCE:

tinymce.init({
    selector: 'textarea',
    plugins: 'codesample',
    toolbar: 'codesample',
    codesample_languages: [
        {text:'HTML/XML',value:'markup'},
        {text:"XML",value:"xml"},
        {text:"HTML",value:"html"},
        {text:"mathml",value:"mathml"},
        {text:"SVG",value:"svg"},
        {text:"CSS",value:"css"},
        {text:"Clike",value:"clike"},
        {text:"Javascript",value:"javascript"},
        {text:"ActionScript",value:"actionscript"},
        {text:"apacheconf",value:"apacheconf"},
        {text:"apl",value:"apl"},
        {text:"applescript",value:"applescript"},
        {text:"asciidoc",value:"asciidoc"},
        {text:"aspnet",value:"aspnet"},
        {text:"autoit",value:"autoit"},
        {text:"autohotkey",value:"autohotkey"},
        {text:"bash",value:"bash"},
        {text:"basic",value:"basic"},
        {text:"batch",value:"batch"},
        {text:"c",value:"c"},
        {text:"brainfuck",value:"brainfuck"},
        {text:"bro",value:"bro"},
        {text:"bison",value:"bison"},
        {text:"C#",value:"csharp"},
        {text:"C++",value:"cpp"},
        {text:"CoffeeScript",value:"coffeescript"},
        {text:"ruby",value:"ruby"},
        {text:"d",value:"d"},
        {text:"dart",value:"dart"},
        {text:"diff",value:"diff"},
        {text:"docker",value:"docker"},
        {text:"eiffel",value:"eiffel"},
        {text:"elixir",value:"elixir"},
        {text:"erlang",value:"erlang"},
        {text:"fsharp",value:"fsharp"},
        {text:"fortran",value:"fortran"},
        {text:"git",value:"git"},
        {text:"glsl",value:"glsl"},
        {text:"go",value:"go"},
        {text:"groovy",value:"groovy"},
        {text:"haml",value:"haml"},
        {text:"handlebars",value:"handlebars"},
        {text:"haskell",value:"haskell"},
        {text:"haxe",value:"haxe"},
        {text:"http",value:"http"},
        {text:"icon",value:"icon"},
        {text:"inform7",value:"inform7"},
        {text:"ini",value:"ini"},
        {text:"j",value:"j"},
        {text:"jade",value:"jade"},
        {text:"java",value:"java"},
        {text:"JSON",value:"json"},
        {text:"jsonp",value:"jsonp"},
        {text:"julia",value:"julia"},
        {text:"keyman",value:"keyman"},
        {text:"kotlin",value:"kotlin"},
        {text:"latex",value:"latex"},
        {text:"less",value:"less"},
        {text:"lolcode",value:"lolcode"},
        {text:"lua",value:"lua"},
        {text:"makefile",value:"makefile"},
        {text:"markdown",value:"markdown"},
        {text:"matlab",value:"matlab"},
        {text:"mel",value:"mel"},
        {text:"mizar",value:"mizar"},
        {text:"monkey",value:"monkey"},
        {text:"nasm",value:"nasm"},
        {text:"nginx",value:"nginx"},
        {text:"nim",value:"nim"},
        {text:"nix",value:"nix"},
        {text:"nsis",value:"nsis"},
        {text:"objectivec",value:"objectivec"},
        {text:"ocaml",value:"ocaml"},
        {text:"oz",value:"oz"},
        {text:"parigp",value:"parigp"},
        {text:"parser",value:"parser"},
        {text:"pascal",value:"pascal"},
        {text:"perl",value:"perl"},
        {text:"PHP",value:"php"},
        {text:"processing",value:"processing"},
        {text:"prolog",value:"prolog"},
        {text:"protobuf",value:"protobuf"},
        {text:"puppet",value:"puppet"},
        {text:"pure",value:"pure"},
        {text:"python",value:"python"},
        {text:"q",value:"q"},
        {text:"qore",value:"qore"},
        {text:"r",value:"r"},
        {text:"jsx",value:"jsx"},
        {text:"rest",value:"rest"},
        {text:"rip",value:"rip"},
        {text:"roboconf",value:"roboconf"},
        {text:"crystal",value:"crystal"},
        {text:"rust",value:"rust"},
        {text:"sas",value:"sas"},
        {text:"sass",value:"sass"},
        {text:"scss",value:"scss"},
        {text:"scala",value:"scala"},
        {text:"scheme",value:"scheme"},
        {text:"smalltalk",value:"smalltalk"},
        {text:"smarty",value:"smarty"},
        {text:"SQL",value:"sql"},
        {text:"stylus",value:"stylus"},
        {text:"swift",value:"swift"},
        {text:"tcl",value:"tcl"},
        {text:"textile",value:"textile"},
        {text:"twig",value:"twig"},
        {text:"TypeScript",value:"typescript"},
        {text:"verilog",value:"verilog"},
        {text:"vhdl",value:"vhdl"},
        {text:"wiki",value:"wiki"},
        {text:"YAML",value:"yaml"}
    ]
});

 

(4)赋值及设置值操作

var context=tinyMCE.activeEditor.getContent();//进行值得获取
 
tinyMCE.activeEditor.setContent("你的数据");//进行值得获取

二、使用prism.js美化网页中的代码

Prism is a lightweight, extensible syntax highlighter.

Prism是一款轻量的,可扩展的语法高亮处理器。

react、MDN、SitePoint、css-tricks等网站都使用该项目

网页中会插入代码。直接把代码放入<pre></pre>标签和<code></code>标签里,也算是可以在页面中显示出来.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>使用prism美化网页中的代码</title>
	<link rel="stylesheet" href="../libaray/prismjs/prism.css">
</head>
<body>
<pre class="line-numbers"><code class="language-javascript">function add(a, b){
	return a + b;
}</code>
</pre>

<script src="../libaray/prismjs/prism.js"></script>
</body>
</html>

 

1、引用网页样式控制文件及脚本语言编辑文件(两个高亮显示脚本)

<link href="prism.css" rel="stylesheet" />
<script src="prism.js"></script>
你的编辑器保存的值取出显示到页面就可以了。
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Prism不同的使用方式</title>
		<!-- 引入prism.css文件 -->
		<link rel="stylesheet" href="./prism.css">
	</head>
	<body>
		<!-- 放置代码位置 -->
		<!-- css代码 -->
		<pre>
			<code class="language-css">
				body{
					background-color: red;
				}
			</code>
		</pre>
		
		<!-- JavaScript代码 -->
		<!-- 使用行号插件和高亮插件 -->
		<pre>
			<code class="language-javascript line-numbers">
				function Person(name, age){
					this.name = name || 'pelli';
					this.age = age || 18;
				}

				Person.prototype.sayHi = function(){
					console.log('Hi, I am ' + this.name + ', I am ' + this.age + ' years old');
				};
			</code>
		</pre>

<!-- JavaScript代码 -->
<!-- 使用行号插件和高亮插件 -->
<pre>
<code class="language-javascript line-numbers">function Person(name, age){
	this.name = name || 'pelli';
	this.age = age || 18;
}

Person.prototype.sayHi = function(){
	console.log('Hi, I am ' + this.name + ', I am ' + this.age + ' years old');
};</code>
</pre>

		<!-- 引入prism.js文件 -->
		<script src="./prism.js"></script>
	</body>
</html>

Supported languages by Prism

This is the list of all 260 languages currently supported by Prism, with their corresponding alias, to use in place of xxxx in the language-xxxx (or lang-xxxx) class:

  • Markup - markup, html, xml, svg, mathml, ssml, atom, rss
  • CSS - css
  • C-like - clike
  • JavaScript - javascript, js
  • ABAP - abap
  • ABNF - abnf
  • ActionScript - actionscript
  • Ada - ada
  • Agda - agda
  • AL - al
  • ANTLR4 - antlr4, g4
  • Apache Configuration - apacheconf
  • Apex - apex
  • APL - apl
  • AppleScript - applescript
  • AQL - aql
  • Arduino - arduino
  • ARFF - arff
  • AsciiDoc - asciidoc, adoc
  • ASP.NET (C#) - aspnet
  • 6502 Assembly - asm6502
  • AutoHotkey - autohotkey
  • AutoIt - autoit
  • Bash - bash, shell
  • BASIC - basic
  • Batch - batch
  • BBcode - bbcode, shortcode
  • Bicep - bicep
  • Birb - birb
  • Bison - bison
  • BNF - bnf, rbnf
  • Brainfuck - brainfuck
  • BrightScript - brightscript
  • Bro - bro
  • BSL (1C:Enterprise) - bsl, oscript
  • C - c
  • C# - csharp, cs, dotnet
  • C++ - cpp
  • CFScript - cfscript, cfc
  • ChaiScript - chaiscript
  • CIL - cil
  • Clojure - clojure
  • CMake - cmake
  • COBOL - cobol
  • CoffeeScript - coffeescript, coffee
  • Concurnas - concurnas, conc
  • Content-Security-Policy - csp
  • Coq - coq
  • Crystal - crystal
  • CSS Extras - css-extras
  • CSV - csv
  • Cypher - cypher
  • D - d
  • Dart - dart
  • DataWeave - dataweave
  • DAX - dax
  • Dhall - dhall
  • Diff - diff
  • Django/Jinja2 - django, jinja2
  • DNS zone file - dns-zone-file, dns-zone
  • Docker - docker, dockerfile
  • DOT (Graphviz) - dot, gv
  • EBNF - ebnf
  • EditorConfig - editorconfig
  • Eiffel - eiffel
  • EJS - ejs, eta
  • Elixir - elixir
  • Elm - elm
  • Embedded Lua templating - etlua
  • ERB - erb
  • Erlang - erlang
  • Excel Formula - excel-formula, xlsx, xls
  • F# - fsharp
  • Factor - factor
  • False - false
  • Firestore security rules - firestore-security-rules
  • Flow - flow
  • Fortran - fortran
  • FreeMarker Template Language - ftl
  • GameMaker Language - gml, gamemakerlanguage
  • G-code - gcode
  • GDScript - gdscript
  • GEDCOM - gedcom
  • Gherkin - gherkin
  • Git - git
  • GLSL - glsl
  • Go - go
  • GraphQL - graphql
  • Groovy - groovy
  • Haml - haml
  • Handlebars - handlebars, hbs
  • Haskell - haskell, hs
  • Haxe - haxe
  • HCL - hcl
  • HLSL - hlsl
  • Hoon - hoon
  • HTTP - http
  • HTTP Public-Key-Pins - hpkp
  • HTTP Strict-Transport-Security - hsts
  • IchigoJam - ichigojam
  • Icon - icon
  • ICU Message Format - icu-message-format
  • Idris - idris, idr
  • .ignore - ignore, gitignore, hgignore, npmignore
  • Inform 7 - inform7
  • Ini - ini
  • Io - io
  • J - j
  • Java - java
  • JavaDoc - javadoc
  • JavaDoc-like - javadoclike
  • Java stack trace - javastacktrace
  • Jexl - jexl
  • Jolie - jolie
  • JQ - jq
  • JSDoc - jsdoc
  • JS Extras - js-extras
  • JSON - json, webmanifest
  • JSON5 - json5
  • JSONP - jsonp
  • JS stack trace - jsstacktrace
  • JS Templates - js-templates
  • Julia - julia
  • Keyman - keyman
  • Kotlin - kotlin, kt, kts
  • KuMir (КуМир) - kumir, kum
  • LaTeX - latex, tex, context
  • Latte - latte
  • Less - less
  • LilyPond - lilypond, ly
  • Liquid - liquid
  • Lisp - lisp, emacs, elisp, emacs-lisp
  • LiveScript - livescript
  • LLVM IR - llvm
  • Log file - log
  • LOLCODE - lolcode
  • Lua - lua
  • Makefile - makefile
  • Markdown - markdown, md
  • Markup templating - markup-templating
  • MATLAB - matlab
  • MEL - mel
  • Mizar - mizar
  • MongoDB - mongodb
  • Monkey - monkey
  • MoonScript - moonscript, moon
  • N1QL - n1ql
  • N4JS - n4js, n4jsd
  • Nand To Tetris HDL - nand2tetris-hdl
  • Naninovel Script - naniscript, nani
  • NASM - nasm
  • NEON - neon
  • Nevod - nevod
  • nginx - nginx
  • Nim - nim
  • Nix - nix
  • NSIS - nsis
  • Objective-C - objectivec, objc
  • OCaml - ocaml
  • OpenCL - opencl
  • OpenQasm - openqasm, qasm
  • Oz - oz
  • PARI/GP - parigp
  • Parser - parser
  • Pascal - pascal, objectpascal
  • Pascaligo - pascaligo
  • PATROL Scripting Language - psl
  • PC-Axis - pcaxis, px
  • PeopleCode - peoplecode, pcode
  • Perl - perl
  • PHP - php
  • PHPDoc - phpdoc
  • PHP Extras - php-extras
  • PL/SQL - plsql
  • PowerQuery - powerquery, pq, mscript
  • PowerShell - powershell
  • Processing - processing
  • Prolog - prolog
  • PromQL - promql
  • .properties - properties
  • Protocol Buffers - protobuf
  • Pug - pug
  • Puppet - puppet
  • Pure - pure
  • PureBasic - purebasic, pbfasm
  • PureScript - purescript, purs
  • Python - python, py
  • Q# - qsharp, qs
  • Q (kdb+ database) - q
  • QML - qml
  • Qore - qore
  • R - r
  • Racket - racket, rkt
  • React JSX - jsx
  • React TSX - tsx
  • Reason - reason
  • Regex - regex
  • Rego - rego
  • Ren'py - renpy, rpy
  • reST (reStructuredText) - rest
  • Rip - rip
  • Roboconf - roboconf
  • Robot Framework - robotframework, robot
  • Ruby - ruby, rb
  • Rust - rust
  • SAS - sas
  • Sass (Sass) - sass
  • Sass (Scss) - scss
  • Scala - scala
  • Scheme - scheme
  • Shell session - shell-session, sh-session, shellsession
  • Smali - smali
  • Smalltalk - smalltalk
  • Smarty - smarty
  • SML - sml, smlnj
  • Solidity (Ethereum) - solidity, sol
  • Solution file - solution-file, sln
  • Soy (Closure Template) - soy
  • SPARQL - sparql, rq
  • Splunk SPL - splunk-spl
  • SQF: Status Quo Function (Arma 3) - sqf
  • SQL - sql
  • Squirrel - squirrel
  • Stan - stan
  • Structured Text (IEC 61131-3) - iecst
  • Stylus - stylus
  • Swift - swift
  • T4 templating - t4-templating
  • T4 Text Templates (C#) - t4-cs, t4
  • T4 Text Templates (VB) - t4-vb
  • TAP - tap
  • Tcl - tcl
  • Template Toolkit 2 - tt2
  • Textile - textile
  • TOML - toml
  • Turtle - turtle, trig
  • Twig - twig
  • TypeScript - typescript, ts
  • TypoScript - typoscript, tsconfig
  • UnrealScript - unrealscript, uscript, uc
  • URI - uri, url
  • V - v
  • Vala - vala
  • VB.Net - vbnet
  • Velocity - velocity
  • Verilog - verilog
  • VHDL - vhdl
  • vim - vim
  • Visual Basic - visual-basic, vb, vba
  • WarpScript - warpscript
  • WebAssembly - wasm
  • Wiki markup - wiki
  • Wolfram language - wolfram, mathematica, nb, wl
  • Xeora - xeora, xeoracube
  • XML doc (.net) - xml-doc
  • Xojo (REALbasic) - xojo
  • XQuery - xquery
  • YAML - yaml, yml
  • YANG - yang
  • Zig - zig

Couldn’t find the language you were looking for? Request it!

【官网】https://prismjs.com/

How to add code snippets using TinyMCE and Prism.js

 

 

TinyMCE  v5

https://www.tiny.cloud/docs/quick-start/

 

https://www.tiny.cloud/docs/plugins/opensource/codesample/