beholdr / commonmark-shortcode
Shortcodes extension for CommonMark
Fund package maintenance!
v0.0.4
2026-04-08 07:52 UTC
Requires
- php: ^8.4
- league/commonmark: ^2.8
Requires (Dev)
- laravel/pint: ^1.0
- pestphp/pest: ^4.0
- phpstan/phpstan: ^2.1
README
Shortcodes extension for CommonMark.
Installation
You can install the package via composer:
composer require beholdr/commonmark-shortcode
Usage
use Beholdr\CommonmarkShortcode\ShortcodeExtension; use Beholdr\CommonmarkShortcode\ShortcodeRegistry; use League\CommonMark\Environment\Environment; use League\CommonMark\MarkdownConverter; // create shortcodes registry $registry = new ShortcodeRegistry(); $registry->register('my-code', fn (array $attrs) => /* Your callback */); // register extension $environment = new Environment(); $environment->addExtension(new ShortcodeExtension($registry)); // use it in markdown $converter = new MarkdownConverter($environment); echo $converter->convert('Markdown with [my-code]!');
You can rebuild a shortcode attribute string using stringify helper:
use Beholdr\CommonmarkShortcode\ShortcodeAttributes; $attrs = ['foo' => 'bar', 'enabled' => true]; ShortcodeAttributes::stringify($attrs); // `foo=bar enabled`
Laravel example
You can use this extension with graham-campbell/markdown or spatie/laravel-markdown packages.
For example, you want to replace [calculator amount=100] shortcode with Livewire component, passing given attributes.
- Register extension in the markdown package config:
'extensions' => [ Beholdr\CommonmarkShortcode\ShortcodeExtension::class, ],
- Bind
ShortcodeRegistryas singleton inside yourAppServiceProviderand register your shortcodes:
use Beholdr\CommonmarkShortcode\ShortcodeAttributes; use Beholdr\CommonmarkShortcode\ShortcodeRegistry; use Illuminate\Support\Facades\Blade; class AppServiceProvider extends ServiceProvider { public function register(): void { $this->app->singleton(ShortcodeRegistry::class, fn () => new ShortcodeRegistry); } public function boot(): void { app(ShortcodeRegistry::class) ->register('calculator', fn ($attrs) => Blade::render( sprintf( '<livewire:calculator %s />', ShortcodeAttributes::stringify($attrs) ) ) ); } }
Testing
composer test
Opencode auth
Put auth.json into .devcontainer/mnt folder and rename it to opencode-auth.json.
License
The MIT License (MIT). Please see License File for more information.