I have moved over from Drupal to Laminas, and a lot of my work continues to involve writing HTML templates. Drupal has a hugely useful Attribute class for manipulating and printing out the attributes of an HTML element: https://git.drupalcode.org/project/drupal/-/blob/9.0.x/core/lib/Drupal/Core/Template/Attribute.php
I really miss Attribute when working with laminas-view. It doesn’t look like laminas-view has anything similar?
If I were to write a laminas-view helper similar to Drupal’s Attribute, are there existing classes/design patterns I should be aware of that might be useful in its creation?
https://docs.laminas.dev/laminas-view/helpers/html-tag/ looks quite close. But the attributes manipulation should work with all elements, and preferably on its own without additional features.
Hello and welcome to the forums!
I like the idea.
The helpers of laminas-view used the following method internally :
protected function htmlAttribs($attribs)
{
$xhtml = '';
$escaper = $this->getView()->plugin('escapehtml');
$escapeHtmlAttr = $this->getView()->plugin('escapehtmlattr');
foreach ((array) $attribs as $key => $val) {
$key = $escaper($key);
if (0 === strpos($key, 'on') || ('constraints' == $key)) {
// Don't escape event attributes; _do_ substitute double quotes with singles
if (! is_scalar($val)) {
// non-scalar data should be cast to JSON first
$val = \Laminas\Json\Json::encode($val);
}
} else {
if (is_array($val)) {
$val = implode(' ', $val);
}
}
This file has been truncated. show original
And laminas-form contains some important extensions for attributes:
use function method_exists;
use function preg_match;
use function sprintf;
use function strlen;
use function strtolower;
use function substr;
/**
* Base functionality for all form view helpers
*/
abstract class AbstractHelper extends BaseAbstractHelper
{
/**
* The default translatable HTML attributes
*
* @var array
*/
protected static $defaultTranslatableHtmlAttributes = [
'title' => true,
];
Nothing special, you can follow the description in the documentation of view helpers .
But I think we need some better names because Drupal’s implementation uses an unbeautiful naming:
Attribute::setAttribute('…');
Attribute::hasAttribute('…');
Attribute::removeAttribute('…');
Attribute::addClass('…');
“Add a class to an attribute” looks wrong.
And the new helper should be used in all other helpers to manage HTML attributes.