因为我的碎语使用的是评论模板,但因为其功能最多支持html,如果想实现复杂的输出,不得不去复制一些复杂的html代码(我之前的一些输出就是这样的),那有没有更好的办法呢?

于是,我想到了短代码,说干就干...

依赖:短代码插件

一、思路

首先,我查看了一下评论内容输出和文章内容输出的区别

评论内容输出语句(/var/Widget/Base/Comments.php)

    /**
     * 获取当前评论内容
     *
     * @return string|null
     */
    protected function ___content(): ?string
    {
        $text = $this->parentContent['hidden'] ? _t('内容被隐藏') : $this->text;

        $text = Comments::pluginHandle()->trigger($plugged)->content($text, $this);
        if (!$plugged) {
            $text = $this->options->commentsMarkdown ? $this->markdown($text)
                : $this->autoP($text);
        }

        $text = Comments::pluginHandle()->contentEx($text, $this);
        return Common::stripTags($text, '<p><br>' . $this->options->commentsHTMLTagAllowed);
    }

文章内容输出语句(/var/Widget/Base/Contents.php)

    /**
     * 获取文章内容
     *
     * @return string|null
     */
    protected function ___content(): ?string
    {
        if ($this->hidden) {
            return $this->text;
        }

        $content = Contents::pluginHandle()->trigger($plugged)->content($this->text, $this);

        if (!$plugged) {
            $content = $this->isMarkdown ? $this->markdown($content)
                : $this->autoP($content);
        }

        return Contents::pluginHandle()->contentEx($content, $this);
    }

都差不多,但是文章内容为什么可以解析短代码呢?

于是,再看看短代码插件的相关内容,在短代码插件 ShortCode.php 文件中,发现最上方已经对 Contents 注册了插件,也就是评论 Comments 也要使用短代码注册才能进行解析。

ps:这里我捣鼓了太久,最后尽量减少修改插件文件,于是直接选择注册 hundle()这个函数。

二、实现

1. 修改插件 ShortCode.php 文件

在最上方给 Comments 对象添加注册插件方法

Typecho_Plugin::factory('Widget_Abstract_Comments')->handle = ['ShortCode', 'handle'];

2. 修改主函数 function.php 文件

添加一个函数

// 评论内容短代码输出功能函数
function commentsContent($comments)
{
    // 解析短代码
    $text = \Widget\Base\Comments::pluginHandle()->trigger($plugged)->handle($comments->text);
    // 解析md代码
    $text = $comments->markdown($text);
    return $text;
}

3. 修改碎语模板文件中(也就是comments.php的复制+css修改版)

在管理员的评论内容输出那里,写入下面的函数调用

echo commentsContent($comments);   

然后在碎语页面中输入一个带短代码的评论,已经可以正常解析短代码了。