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 (the host of a remote one reaches the CSP's style-src)
$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->addInlineStyle('body { background-color: #f0f0f0; }');

// Critical scripts should load first (sort_order = 1)
$headManager->createElement('script', [
    'attributes' => ['src' => $block->getViewFileUrl('js/critical.js')],
    'sort_order' => 1
]);

// Viewport meta tag with high priority (sort_order = 5)
$headManager->createElement('meta', [
    'attributes' => ['name' => 'viewport', 'content' => 'width=device-width, initial-scale=1'],
    'sort_order' => 5
]);

// Regular stylesheet uses default sort_order (100)
$headManager->addStylesheet($block->getViewFileUrl('css/styles.css'));

// Deferred scripts load later (sort_order = 200)
$headManager->createElement('script', [
    'attributes' => ['src' => $block->getViewFileUrl('js/analytics.js'), 'defer' => true],
    'sort_order' => 200
]);

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()] : [];
    }
}

$headTagManager->createElement('custom', [
    'attributes' => ['data-custom' => 'value'],
    'content' => 'Custom Content'
], 'custom_key');
xml
<type name="Hryvinskyi\HeadTagManager\Model\Registry\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\Model\Serializer\Strategy\SerializationStrategyRegistry">
    <arguments>
        <argument name="strategies" xsi:type="array">
            <item name="custom" xsi:type="object">Vendor\Module\Strategy\CustomElementSerializationStrategy</item>
        </argument>
    </arguments>
</type>