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



/** @var \Hryvinskyi\HeadTagManager\ViewModel\HeadTagManagerViewModel $headTagManagerViewModel */
$headTagManagerViewModel = $block->getData('head_tag_manager_view_model');
$headManager = $headTagManagerViewModel->getManager();

// Add preconnect link
$headTagManagerViewModel->getManager()->addLink([
    'rel' => 'preload',
    'href' => 'https://example.com/image.jpg',
    'as' => 'image',
]);

// Add prefetch link
$headTagManagerViewModel->getManager()->addLink([
    'rel' => 'prefetch',
    'href' => '/landing-page',
]);

// Add DNS prefetch link
$headTagManagerViewModel->getManager()->addLink([
    'rel' => 'dns-prefetch',
    'href' => 'https://fonts.googleapis.com/',
]);

// Add stylesheets (CSP compatible)
$headManager->addStylesheet($block->getViewFileUrl('css/some-custom.css'));

// Add external scripts (CSP compatible)
$headManager->addExternalScript($block->getViewFileUrl('js/some-custom.js'));

// Add inline script (CSP compatible)
$headManager->addInlineScript('console.log("Hello, world!");');

// Add inline styles (CSP compatible)
$headManager->addStyle('body { background-color: #f0f0f0; }');

class CustomElement implements HeadElementInterface
{
    private $attributes;
    private $content;

    public function __construct(array $attributes, string $content)
    {
        $this->attributes = $attributes;
        $this->content = $content;
    }

    public function getAttributes(): array
    {
        return $this->attributes;
    }

    public function getContent(): string
    {
        return $this->content;
    }
    
    /**
     * Render the head element as HTML
     * @return string The HTML representation of the element
     */
    public function render(): string
    {
        $attributes = '';
        foreach ($this->attributes as $key => $value) {
            $attributes .= sprintf(' %s="%s"', htmlspecialchars($key), htmlspecialchars($value));
        }
        return sprintf('<custom-element%s>%s</custom-element>', $attributes, htmlspecialchars($this->content));
    }
}

class CustomElementFactory extends extends AbstractHeadElementFactory
{
    /**
     * @inheritDoc
     */
    public function create(array $data = []): HeadElementInterface
    {
        return new CustomElement(
            $data['attributes'] ?? [],
            $data['content'] ?? ''
        );
    }

    /**
     * @inheritDoc
     */
    public function getElementType(): string
    {
        return 'custom';
    }

    /**
     * @inheritDoc
     */
    public function getElementClassName(): string
    {
        return CustomElement::class;
    }
}

class CustomElementSerializationStrategy implements HeadElementSerializationStrategyInterface
{
    public function serialize(HeadElementInterface $element, string $key): array
    {
        return [
            'type' => get_class($element),
            'short_type' => $element->getElementType(),
            'attributes' => $element->getAttributes(),
            'content' => $element->getContent()
        ];
    }

    public function getElementType(): string
    {
        return 'custom';
    }
}

$headTagManager->createElement('custom', [
    'attributes' => ['data-custom' => 'value'],
    'content' => 'Custom Content'
], 'custom_key');

class CustomElementStrategy implements HeadElementSerializationStrategyInterface
{
    public function serialize(HeadElementInterface $element, string $key): array
    {
        return [
            'type' => get_class($element),
            'short_type' => $this->getElementType(),
            'attributes' => $element->getAttributes(),
            'content' => $this->extractContent($element)
        ];
    }
}
xml
<type name="Hryvinskyi\HeadTagManager\Factory\HeadElementFactoryRegistry">
    <arguments>
        <argument name="factories" xsi:type="array">
            <item name="custom" xsi:type="object">Vendor\Module\Factory\CustomElementFactory</item>
        </argument>
    </arguments>
</type>
<type name="Hryvinskyi\HeadTagManager\Strategy\SerializationStrategyRegistry">
    <arguments>
        <argument name="strategies" xsi:type="array">
            <item name="custom" xsi:type="object">Vendor\Module\Strategy\CustomElementSerializationStrategy</item>
        </argument>
    </arguments>
</type>