Skip to content
This repository has been archived by the owner on Feb 16, 2024. It is now read-only.

Latest commit

 

History

History
90 lines (61 loc) · 2.72 KB

README.md

File metadata and controls

90 lines (61 loc) · 2.72 KB

This project has been archived. If you are using Laravel, see Illuminate\View\ComponentAttributeBag.

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\";)"