tehwave/laravel-shortcodes
Composer 安装命令:
composer require tehwave/laravel-shortcodes
包简介
Simple, elegant WordPress-like Shortcodes the Laravel way
README 文档
README
Laravel Shortcodes
Simple, elegant WordPress-like Shortcodes the Laravel way.
Requirements
The package has been developed and tested to work with the latest supported versions of PHP and Laravel as well as the following minimum requirements:
- Laravel 12
- PHP 8.2
Version Compatibility
| Laravel | PHP | Branch |
|---|---|---|
| 13 | 8.3 - 8.5 | master |
| 12 | 8.2 - 8.5 | master |
| 11 | 8.2 - 8.4 | 2.x |
| 10 and below | 8.1 and below | 1.x |
Installation
Install the package via Composer.
composer require tehwave/laravel-shortcodes
Usage
Laravel Shortcodes work much like WordPress' Shortcode API.
<?php use tehwave\Shortcodes\Shortcode; $compiledContent = Shortcode::compile('[uppercase]Laravel Shortcodes[/uppercase]'); // LARAVEL SHORTCODES
Creating Shortcodes
Run the following command to place a fresh Shortcode class in your new app/Shortcodes directory.
php artisan make:shortcode ItalicizeText
Output
Each Shortcode class contains a handle method, that you may use to output into the compiling content.
Within the handle method, you may access the attributes and body properties.
Note
All values in the attributes array are cast to string type when parsed unless specifically cast to a type via the $casts property.
<?php namespace App\Shortcodes; use tehwave\Shortcodes\Shortcode; class ItalicizeText extends Shortcode { /** * The code to run when the Shortcode is being compiled. * * You may return a string from here, that will then * be inserted into the content being compiled. * * @return string|null */ public function handle(): ?string { if (isset($this->attributes['escape_html']) && $this->attributes['escape_html'] === 'true')) { return sprintf('<i>%s</i>', htmlspecialchars($this->body)); } return sprintf('<i>%s</i>', $this->body); } }
Naming
The shortcode's tag is derived from the class name to snake_case.
You may specify a custom tag using the tag property or by overwriting the getTag method.
Shortcode tags must be alpha-numeric characters and may include underscores.
<?php namespace App\Shortcodes; use tehwave\Shortcodes\Shortcode; class ItalicizeText extends Shortcode { /** * The tag to match in content. * * @var string */ protected $tag = 'italics'; }
Compiling Shortcodes
Run a string through the compiler to parse all shortcodes.
<?php use tehwave\Shortcodes\Shortcode; $compiledContent = Shortcode::compile('[italics escape_html="true"]<b>Hello World</b>[/italics]'); // <i><b>Hello World</b></i>
You may specify a list of instantiated Shortcode classes to limit what shortcodes are parsed.
<?php use tehwave\Shortcodes\Shortcode; $shortcodes = collect([ new ItalicizeText, ]); $compiledContent = Shortcode::compile('[uppercase]Hello World[/uppercase]', $shortcodes); // [uppercase]Hello World[/uppercase]
Using Casts
Laravel Shortcodes supports casting attributes to various data types. This can be useful when you need to ensure that the attributes passed to your shortcodes are of a specific type.
Available Casts
booleanintegerfloatstringarraycollectionobjectjsonencryptedhasheddate(casts toCarbon\Carboninstance)
Example
To use casts, you need to create a shortcode class and specify the casts in the $casts property.
<?php namespace App\Shortcodes; use tehwave\Shortcodes\Shortcode; use Carbon\Carbon; class ExampleShortcode extends Shortcode { /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'is_active' => 'boolean', 'count' => 'integer', 'price' => 'float', 'name' => 'string', 'tags' => 'array', 'options' => 'collection', 'metadata' => 'object', 'config' => 'json', 'published_at' => 'date', ]; /** * The code to run when the Shortcode is being compiled. * * @return string|null */ public function handle(): ?string { $publishedAt = $this->attributes['published_at'] instanceof Carbon ? $this->attributes['published_at']->toFormattedDateString() : 'N/A'; $tags = implode(', ', $this->attributes['tags']); $options = $this->attributes['options']->implode(', '); return sprintf( 'Active: %s, Count: %d, Price: %.2f, Name: %s, Published At: %s, Tags: %s, Options: %s', $this->attributes['is_active'] === true ? 'Yes' : 'No', $this->attributes['count'], $this->attributes['price'], $this->attributes['name'], $publishedAt, $tags, $options ); } }
When you compile content with this shortcode, the attributes will be automatically cast to the specified types.
<?php use tehwave\Shortcodes\Shortcode; $compiledContent = Shortcode::compile('[example is_active="1" count="10" price="99.99" name="Sample" published_at="2023-06-29" tags=\'["tag1","tag2","tag3"]\' options=\'["option1","option2"]\']'); // Active: Yes, Count: 10, Price: 99.99, Name: Sample, Published At: Jun 29, 2023, Tags: tag1, tag2, tag3, Options: option1, option2
Accessing Attributes
You can retrieve the attributes as direct properties of the shortcode instance.
<?php namespace App\Shortcodes; use tehwave\Shortcodes\Shortcode; class ExampleShortcode extends Shortcode { protected $casts = [ 'is_active' => 'boolean', 'count' => 'integer', ]; public function handle(): ?string { // Access attributes as properties $isActive = $this->is_active; $count = $this->count; return sprintf('Active: %s, Count: %d', $isActive === true ? 'Yes' : 'No', $count); } }
Example
I developed Laravel Shortcodes for use with user provided content on gm48.net.
The content is parsed using a Markdown converter called Parsedown, and because users can't be trusted, the content has to be escaped.
Unfortunately, this escapes the attribute syntax with double quotes, but singular quotes can still be used as well as just omitting any quotes.
Note
Quotes are required for any attribute values that contain whitespace.
Let's take a look at the following content with some basic Row, Columnand Image shortcodes.
# Controls:
[row]
[column]
[image align=left src=http://i.imgur.com/6CNoFYx.png alt='Move player character']
[/column]
[column]
[image align=center src=http://i.imgur.com/8nwaVo0.png alt=Jump]
[/column]
[column]
[image align=right src=http://i.imgur.com/QsbkkuZ.png alt='Go down through platforms']
[/column]
[/row]
When running the content through the following code:
$parsedDescription = (new Parsedown()) ->setSafeMode(true) ->setUrlsLinked(false) ->text($this->description); $compiledDescription = Shortcode::compile($parsedDescription);
We can expect to see the following output:
<h1>Controls:</h1> <p></p> <div class="container-fluid"> <div class="row"> <div class="col"> <img src="http://i.imgur.com/6CNoFYx.png" class="mr-auto" alt="Move player character"> </div> <div class="col"> <img src="http://i.imgur.com/8nwaVo0.png" class="mx-auto" alt="Jump"> </div> <div class="col"> <img src="http://i.imgur.com/QsbkkuZ.png" class="ml-auto" alt="Go down through platforms"> </div> </div> </div>
You should still escape any user input within your shortcodes' handle.
Tests
Run the following command to test the package.
composer test
Security
For any security related issues, send a mail to peterchrjoergensen+shortcodes@gmail.com instead of using the issue tracker.
Changelog
See CHANGELOG for details on what has changed.
Upgrade Guide
See UPGRADING.md for details on how to upgrade.
Contributions
See CONTRIBUTING for details on how to contribute.
Credits
Inspired by https://github.com/webwizo/laravel-shortcodes and https://github.com/spatie/laravel-blade-x
About
I work as a Web Developer in Denmark on Laravel and WordPress websites.
Follow me @tehwave on Twitter!
License
tehwave/laravel-shortcodes 适用场景与选型建议
tehwave/laravel-shortcodes 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 80.5k 次下载、GitHub Stars 达 12, 最近一次更新时间为 2019 年 12 月 21 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「package」 「php」 「wordpress」 「laravel」 「shortcodes」 「tehwave」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 tehwave/laravel-shortcodes 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 tehwave/laravel-shortcodes 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 tehwave/laravel-shortcodes 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Simple ASCII output of array data
Alfabank REST API integration
Package for view storage in laravel
User Approval Laravel Package
Must-use plugin integrating WordPress with the Upsun platform: environment awareness, router-cache friendliness, safe preview clones, deploy migrations, Site Health checks, and a wp upsun CLI command.
统计信息
- 总下载量: 80.5k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 12
- 点击次数: 12
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2019-12-21