将您自己的类添加到 Spatie laravel markdown 中渲染的 markdown 中

问题描述 投票:0回答:1

我正在尝试使用 Spatie laravel markdown 包创建一个博客网站。我已经成功了。我将降价保存在帖子表的字段中。降价在我的刀片视图中呈现

div class="md:w-2/3  max-w-none text-white over">
        <x-markdown>
                {!! $post->content !!}
</x-markdown>
</div>

但是我无法弄清楚如何将一些额外的类注入到渲染的降价中。具体来说,我想在保存的 Markdown 中的围栏代码周围添加一些填充和边距

如有任何帮助,我们将不胜感激

laravel markdown
1个回答
0
投票

config/markdown.php
中,将自定义渲染器添加到扩展数组中:

use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
use League\CommonMark\Extension\CommonMark\Renderer\Block\FencedCodeRenderer;
use League\CommonMark\Util\HtmlElement;

return [

    'extensions' => [
        // Add this custom fenced code block renderer
        'custom-fenced-code' => function () {
            return new class extends FencedCodeRenderer {
                public function render($node, \League\CommonMark\Output\RenderedContentInterface $childRenderer) {
                    if (!($node instanceof FencedCode)) {
                        throw new \InvalidArgumentException('Incompatible block type: ' . get_class($node));
                    }

                    $attrs = $node->getData('attributes', []);
                    $attrs['class'] = ($attrs['class'] ?? '') . ' my-custom-code-class p-4 my-4'; // Add your custom classes here

                    return new HtmlElement(
                        'pre',
                        ['class' => 'bg-gray-800 text-white'], // Pre tag custom classes
                        new HtmlElement(
                            'code',
                            $attrs,
                            htmlspecialchars($node->getStringContent())
                        )
                    );
                }
            };
        },
    ],

];

上面的例子是使用 Tailwind css。您可以从其他框架更改为其他类。如果您想使用

style
属性,请直接将
$attrs['class']
更改为:

$attrs['style'] = ($attrs['style'] ?? '') . 'padding: 20px; margin: 15px 0; background-color: #2d2d2d; color: #f8f8f2; border-radius: 5px;';
php artisan vendor:publish --provider="Spatie\LaravelMarkdown\MarkdownServiceProvider" --tag="markdown-config"

请注意,您需要运行

php artisan vendor:publish --provider="Spatie\LaravelMarkdown\MarkdownServiceProvider" --tag="markdown-config"
才能获得
config/markdown.php

© www.soinside.com 2019 - 2024. All rights reserved.