PHP code example of hryvinskyi / magento2-head-tag-manager
1. Go to this page and download the library: Download hryvinskyi/magento2-head-tag-manager library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hryvinskyi / magento2-head-tag-manager example snippets
class CustomElement extends AbstractHeadElement
{
private ?string $content = null;
public function __construct(
private readonly AttributeRendererInterface $attributeRenderer,
array $attributes = [],
int $sortOrder = 100
) {
parent::__construct($attributes, $sortOrder);
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function render(): string
{
return '<custom-element' . $this->attributeRenderer->render($this->getAttributes()) . '>'
. htmlspecialchars((string) $this->content, ENT_QUOTES)
. '</custom-element>';
}
}
class CustomElementFactory extends AbstractHeadElementFactory
{
/**
* @param \Vendor\Module\Model\CustomElementFactory $elementFactory Magento's generated factory for the element
*/
public function __construct(
private readonly \Vendor\Module\Model\CustomElementFactory $elementFactory
) {
}
protected function createElement(array $data): AbstractHeadElement
{
$element = $this->elementFactory->create();
if (isset($data['content'])) {
$element->setContent($data['content']);
}
return $element;
}
protected function getDefaultSortOrder(): int
{
return 100;
}
public function getElementType(): string
{
return 'custom';
}
public function getElementClassName(): string
{
return CustomElement::class;
}
}
class CustomElementSerializationStrategy extends AbstractSerializationStrategy
{
public function getElementType(): string
{
return 'custom';
}
public function getElementClassName(): string
{
return CustomElement::class;
}
protected function getAdditionalSerializationData(HeadElementInterface $element): array
{
return $element instanceof CustomElement ? ['content' => $element->getContent()] : [];
}
}