定制 jtolj/html-attributes 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

jtolj/html-attributes

最新稳定版本:v2.1.0

Composer 安装命令:

composer require jtolj/html-attributes

包简介

A Fluent Interface for Handling HTML Attributes in PHP.

README 文档

README

A Fluent Interface for Handling HTML Attributes in PHP

The package provides a simple class, inspired by Drupal's Drupal\Core\Template\Attribute, to help manage HTML attributes in a structured way.

I use it primarily in Laravel, so the pseudocode examples below use Laravel conventions. The package, however, is not specific to Laravel and can be used without it.

Examples

In a Controller

use App\Post;
use Jtolj\HtmlAttributes\HtmlAttributes;

$post = Post::find(1);
$post->is_wide = true;
$attributes = new HtmlAttributes();
$attributes
    ->addClass('card');
    ->setAttribute('id', "post-{$post->id}");
$attributes->addClassIf('card--wide', $post->is_wide);

echo "<div $attributes>$post->escaped_content</div>"

Output

<div class="card card--wide" id="post-1">Hello World</div>

Using the example Trait with a Eloquent model and Blade template:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Jtolj\HtmlAttributes\Traits\HasHtmlAttributes;
class Post extends Model
{
    use HasHtmlAttributes;
}
@foreach ($posts as $post)
    <div {!! $post->htmlAttributes()->addClass('card')->addClassIf('even', $loop->even) !!}>
    {{ $post->summary }}
    </div>
@endforeach

Output

<div class="card">First Post</div>
<div class="card even">Second Post</div>
<div class="card">Third Post</div>

Escaping and Filtering

Escaping of attribute names and values is done using the laminas/laminas-escaper package. Attribute keys are escaped using the escapeHtmlAttr() method. As of 2.0, attribute values are escaped using the escapeHtml() method.

Additionally, by default attribute names starting with 'on' (javascript event handlers) are not output.

You can set your own list of stripped prefixes with the setUnsafePrefixes(array $prefixes) method. Attribute names beginning with those prefixes are stripped on output.

You can also turn this behavior off by calling allowUnsafe(). This will not filter the list of attribute names before output and will output the value of 'unsafe' attributes fully unescaped (as of 2.0). Be extremely careful with this behavior to prevent XSS.

use Jtolj\HtmlAttributes\HtmlAttributes;

$attributes = new HtmlAttributes;
$attributes->addClass('card');
$attribute->setAttribute('onclick', 'alert("Hello";)');

$safe_string = (string) $attributes;
//class="card"

$attributes->allowUnsafe();
$unsafe_string = (string) $attributes;
//class="card" onclick="alert(\"Hello\";)"

统计信息

  • 总下载量: 78.1k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-08-07