PHPackages                             pjkui/yii2-markdown - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. pjkui/yii2-markdown

ActiveYii2-extension[Templating &amp; Views](/categories/templating)

pjkui/yii2-markdown
===================

Markdown editor for Yii2

v1.6.1(2mo ago)0164Apache-2.0PHPPHP &gt;=8.1CI passing

Since May 15Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/pjkui/yii2-markdown)[ Packagist](https://packagist.org/packages/pjkui/yii2-markdown)[ RSS](/packages/pjkui-yii2-markdown/feed)WikiDiscussions master Synced today

READMEChangelog (3)Dependencies (4)Versions (16)Used By (0)

yii2-markdown
=============

[](#yii2-markdown)

[![CI](https://github.com/pjkui/yii2-markdown/actions/workflows/ci.yml/badge.svg)](https://github.com/pjkui/yii2-markdown/actions/workflows/ci.yml)[![codecov](https://camo.githubusercontent.com/ecb89f21af308e69241f2f4b5682e310ba5d622d94842fcce6f45db735324e0a/68747470733a2f2f636f6465636f762e696f2f67682f706a6b75692f796969322d6d61726b646f776e2f67726170682f62616467652e737667)](https://codecov.io/gh/pjkui/yii2-markdown)[![Latest Stable Version](https://camo.githubusercontent.com/00573791f5e651ffb560336d4a5f0480e53940d27fd944da31e308cec660e7da/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f706a6b75692f796969322d6d61726b646f776e2e737667)](https://packagist.org/packages/pjkui/yii2-markdown)[![Total Downloads](https://camo.githubusercontent.com/b62948d5d06111cfae8707dbaf9125d46b6baba5862a4a75388f79a60c29f714/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f706a6b75692f796969322d6d61726b646f776e2e737667)](https://packagist.org/packages/pjkui/yii2-markdown)[![License](https://camo.githubusercontent.com/5466af124fe3bb8964192b568cccb967bc3c433da81bd770ee2a5c8f1210a179/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f706a6b75692f796969322d6d61726b646f776e2e737667)](https://packagist.org/packages/pjkui/yii2-markdown)[![PHP](https://camo.githubusercontent.com/04744bae0a61d2ffe29c26f07a9612eae20445fc6feaeb77b3af1f0e9be6447c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d3838393242462e737667)](https://packagist.org/packages/pjkui/yii2-markdown)

`yii2-markdown` 是一个基于 [Cherry Markdown](https://github.com/Tencent/cherry-markdown) 与 [Vditor](https://github.com/Vanessa219/vditor) 封装的 Yii2 扩展，支持 **双引擎**——用户可在编辑器工具栏中随时在 Markdown 源码模式与所见即所得（WYSIWYG）模式之间切换，无需刷新页面。

**核心能力：**

- Markdown 编辑器组件 `pjkui\markdown\Editor`（Cherry Markdown 引擎）
- 所见即所得编辑器组件 `pjkui\markdown\VditorEditor`（Vditor 引擎）
- 只读预览组件 `pjkui\markdown\Preview`
- 工具栏一键切换，带确认对话框 + 一键放弃转换横幅
- 文件上传、草稿自动保存（LocalStorage）、快捷键提交（Ctrl/⌘+S）、字数统计
- 深色模式跟随 `data-theme="dark"`

---

安装
--

[](#安装)

```
composer require pjkui/yii2-markdown
```

---

快速开始
----

[](#快速开始)

### 纯 Markdown 模式（默认）

[](#纯-markdown-模式默认)

```
use pjkui\markdown\Editor;

echo Editor::widget([
    'model'     => $model,
    'attribute' => 'content',
    'options'   => [
        'url'   => '/upload',       // 文件上传接口
        'extra' => ['type' => 'md'],
    ],
]);
```

### 所见即所得模式（WYSIWYG）

[](#所见即所得模式wysiwyg)

```
echo Editor::widget([
    'model'      => $model,
    'attribute'  => 'content',
    'isMarkdown' => false,           // 启动即 WYSIWYG（Vditor）
    'options'    => ['url' => '/upload'],
]);
```

### 双引擎可切换（推荐）

[](#双引擎可切换推荐)

默认以 Markdown 模式启动，工具栏末尾自动注入蓝色 **V** 按钮（切换到 WYSIWYG），切换后变为蓝色 **M** 按钮（切回 Markdown）。

**必须在页面中注册资源**，否则切换时 Vditor 未加载会失败：

```
use pjkui\markdown\Editor;
use pjkui\markdown\ConverterAsset;
use pjkui\markdown\VditorAsset;

// 预加载双引擎资源（包含 dual-engine-controller.js）
ConverterAsset::register($this); // $this = \yii\web\View
VditorAsset::register($this);

echo Editor::widget([
    'model'     => $model,
    'attribute' => 'content',
    'options'   => ['url' => '/upload'],
]);
```

**表单后端接收**（切换后会多出 `_md` / `_html` 两个隐藏字段）：

```
public function rules(): array
{
    return [
        [['content', 'content_md', 'content_html'], 'string'],
    ];
}

public function beforeSave($insert): bool
{
    if (!parent::beforeSave($insert)) return false;
    // 以 Markdown 为权威源，HTML 用作展示缓存
    if (!empty($this->content_md)) {
        $this->content = $this->content_md;
    }
    return true;
}
```

---

只读预览
----

[](#只读预览)

```
use pjkui\markdown\Preview;

echo Preview::widget([
    'value' => $model->content,  // Markdown 字符串
]);
```

---

切换事件监听
------

[](#切换事件监听)

```
document.addEventListener('yii2md:beforeSwitch', e => {
    console.log('即将切换', e.detail); // { instanceId, from, to }
});
document.addEventListener('yii2md:afterSwitch', e => {
    console.log('已切换到', e.detail.to);
});
document.addEventListener('yii2md:revert', e => {
    console.log('已放弃本次转换', e.detail);
});
```

---

编程式切换
-----

[](#编程式切换)

```
// 切换到所见即所得
window.Yii2Markdown.DualEngine.switchTo('vditor');

// 切换到 Markdown
window.Yii2Markdown.DualEngine.switchTo('cherry');

// 放弃本次转换，恢复切换前的内容和模式
window.Yii2Markdown.DualEngine.revert();
```

---

目录结构
----

[](#目录结构)

```
src/
  Editor.php            # 统一入口（按 isMarkdown 路由到 Cherry / Vditor）
  VditorEditor.php      # Vditor WYSIWYG 引擎
  Preview.php           # 只读预览
  EditorAsset.php       # Cherry 资源包
  VditorAsset.php       # Vditor 资源包
  ConverterAsset.php    # Markdown↔HTML 互转 + DualEngine 控制器
  dist/
    cherry-markdown.js/css
    vditor/
    dual-engine-controller.js  # 双引擎切换逻辑
    converter.js               # Markdown↔HTML 互转 API
docs/
  usage.md
  configuration.md
  migration-guide.md    # 双引擎升级指南
examples/
  index.php             # 本机可视化 Demo（composer demo 启动）

```

---

本机 Demo
-------

[](#本机-demo)

```
composer demo
# 访问 http://127.0.0.1:8080/
```

Demo 页支持：

- Cherry ↔ Vditor 工具栏一键切换（含放弃转换）
- 深色 / 浅色主题切换（🌙/☀️）
- 文件上传、草稿恢复、表单提交回显

---

文档
--

[](#文档)

文档说明[usage.md](./docs/usage.md)完整使用示例[configuration.md](./docs/configuration.md)所有配置项说明[migration-guide.md](./docs/migration-guide.md)v1.3+ 双引擎升级指南[testing.md](./docs/testing.md)测试与可视化验证---

测试
--

[](#测试)

项目同时维护 **PHPUnit**、**Jest** 和 **Playwright** 三套测试，共 **78 tests**。每次 push 到 `master` 或创建 PR 时，GitHub Actions 会自动运行全套测试（PHP 8.1/8.2/8.3 × msedge）。

```
# 一键跑所有测试
npm run test:all

# 分类运行
npm run test:php    # PHPUnit（18 tests）
npm test            # Jest 单元测试（34 tests）
npm run test:e2e    # Playwright E2E（26 tests）
```

首次运行前安装依赖：

```
composer install && npm install
npx playwright install --with-deps msedge
```

### 测试套件

[](#测试套件)

目录工具内容`tests/`PHPUnitPHP 组件单元 + 集成测试`tests/unit/converter/`JestMarkdown↔HTML 转换器，含覆盖率（93%）`tests/e2e/`Playwright双引擎切换 E2E 回归（T1–T9、E1–E7、R1–R6）

###  Health Score

46

—

FairBetter than 92% of packages

Maintenance87

Actively maintained with recent releases

Popularity13

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~103 days

Recently: every ~0 days

Total

15

Last Release

65d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/6873307?v=4)[Quinn Pan](/maintainers/pjkui)[@pjkui](https://github.com/pjkui)

---

Top Contributors

[![pjkui](https://avatars.githubusercontent.com/u/6873307?v=4)](https://github.com/pjkui "pjkui (53 commits)")

---

Tags

yii2extension

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/pjkui-yii2-markdown/health.svg)

```
[![Health](https://phpackages.com/badges/pjkui-yii2-markdown/health.svg)](https://phpackages.com/packages/pjkui-yii2-markdown)
```

###  Alternatives

[craftcms/cms

Craft CMS

3.6k3.6M3.1k](/packages/craftcms-cms)[raoul2000/yii2-bootswatch-asset

Use Bootswatch theme in your Yii application with minimum effort

2045.5k4](/packages/raoul2000-yii2-bootswatch-asset)[zxbodya/yii2-tinymce

Yii2 extension to use TinyMce with Compressor and FileManager

1732.9k3](/packages/zxbodya-yii2-tinymce)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
