上一篇文章Typecho GithubCorner小插件开发记录—从Hello World开始介绍了Typecho 插件开发的基础知识。本博文讲记录一些GithubCorner这个在页面右上角显示Github图标链接的小插件开发过程要点。完整的插件代码如下,如果喜欢请点亮一颗小星星

根据之前说的无脑实现接口中的函数,然后在activate 函数中注册渲染函数到页面的header 渲染接口当中。

1
2
3
4
5
/** * 激活插件方法,如果激活失败,直接抛出异常 */ public static function activate() { \Typecho\Plugin::factory('Widget_Archive')->header = __CLASS__ . '::render'; }

然后去编写我们的渲染函数render ,然后明确我们的这个header渲染就是在body的最前方。我们要做的就是输出一个<a> 标签并固定在页面的右上角。具体HTML代码请参考这个项目github-corners

1
2
3
4
<a href="" class="github-corner" aria-label="View source on GitHub"> <svg width="72" height="72" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: fixed; top: 1; border: 0; right: 0; z-index: 1021;" aria-hidden="true"> ... </svg> </a>

我们直接把这个corner组件的代码先写入到一个同文件夹的Corner.php文件下面,然后在render函数中调用输出这个php文件

1
2
3
4
5
6
7
/** * 插件实现方法 * * @access public * @return void */ public static function render() { require_once 'Corner.php'; }

在配置中启用插件,就可以看到任何页面的右上角都会有一个Github 的小角标。

t0bCqrvBzLwyEaB9ZUK3-uaZhIxysNUMl8yFIFWh2BA.png

然后我们增加配置相关的表单功能实现链接跳转地址的设置和显示设置。在配置中增加Github Profile 的跳转地址和是否显示角标的复选框。

1
2
3
4
5
6
7
8
9
/** * 获取插件配置面板 * * @param Form $form 配置面板 */ public static function config(Form $form) { $profile = new Text('profile', null, 'https://', _t('Github Profile')); $form->addInput($profile); $check = new Checkbox('showProfileOptions', [ 'Show' => _t('在主页上显示Github Corner Profile'), ], [], _t('是否在主页上显示Github Corner')); $form->addInput($check->multiMode()); }

完成后就可以在设置中进行配置

lK6eARTZ10XgKIIwU7Heiv8E25yt3A0jJZGG9zNppR8.png

然后我们修改render 函数以支持配置选项,并判断页面是文章列表还是博客文章以实现在博客文章实现不同的仓库跳转。

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
/** * 插件实现方法 * * @access public * @return void */ public static function render(...$args) { $widget = null; foreach ($args as $key => $value) { // var_dump(gettype($value)); if(gettype($value) == 'object') { // check the archive instance $valid = $value instanceof Archive; if ($valid) { $widget = $value; } } } if (!is_null($widget)) { $githubUrl = ""; if ($widget->getArchiveType() == 'index') { // show profile on index $profile = Options::alloc()->plugin('GithubCorner')->profile; $showOption = Options::alloc()->plugin('GithubCorner')->showProfileOptions; if ($showOption != null && count($showOption, COUNT_NORMAL) > 0) { // show profile options is checked // echo $profile; $githubUrl = $profile; require_once 'Corner.php'; } } else { // check the data show if `repository` field is existed. // var_dump($widget->getArchiveType()); // echo $widget->getArchiveType(); $field = $widget->fields->repository; if (!is_null($field)) { $githubUrl = $field; require_once 'Corner.php'; } } } }

在文章中想要跳转到不同的仓库,仅需要在文章编辑页面加入一个自定义字段repository 并填入对应的仓库地址,在文章页面显示的Github 角标就会跳转到对应仓库了。如果没有改字段,则不会显示角标。

g2QwFDIIAsUDu_VYMi2DuosVZCQQkKQJEWDMUkZSot8.png