Hyvä CMS Component Templates
This page is a reference for building Hyvä CMS component PHTML templates: the Element block helper methods, and patterns for rendering links, child components, images, and CSS classes. To create a component from scratch, see Creating Components.
Default Template Path
You can omit the template property from your component declaration. When omitted, Hyvä CMS uses a default template path based on the component name: [Vendor]_[Module]::elements/[component-name].phtml
Hyvä CMS Component Block Helper Methods
The Hyva\CmsLiveviewEditor\Block\Element class provides essential helper methods for building Hyvä CMS component templates. These methods handle common tasks like editor integration, image processing, link handling, and child component rendering.
Essential Block Methods Reference
Below is a summary of the most useful methods available in your Hyvä CMS component templates. These methods are part of the Hyva\CmsLiveviewEditor\Block\Element class. Review the class source code for complete details.
getEditorAttrs
Adds special attributes that allow the Hyvä CMS liveview editor to interact with content in preview mode.
When a user clicks on content in the Hyvä CMS preview mode, these attributes ensure the correct form field opens for editing. These attributes are only added in preview mode and are automatically removed from the final rendered output on the frontend.
Example usage in component template:
// Root-level editor attributes are injected automatically into the first element.
// You usually only need field-specific calls like getEditorAttrs('title').
// Field-specific - enables direct field editing
<h2 <?= /** @noEscape */ $block->getEditorAttrs('title') ?>>
renderEditorMessage
Renders a message visible only in the Hyvä CMS editor preview, not on the public frontend.
This method is useful for showing placeholder messages when a component has no content or when a required field is empty. The message only appears in the CMS editor and helps guide content editors.
Example usage for missing image placeholder:
<?= /** @noEscape */ $block->renderEditorMessage([
'preview_message' => __('No image selected'),
'button_text' => __('Select Image'),
]) ?>
validPreview
Checks if the current request is a valid Hyvä CMS preview request.
Returns false when rendering public-facing content on the frontend. Returns true when viewing a preview of the content in a new tab or from within the Hyvä CMS editor. Use this method to conditionally add content that should only appear in preview mode, such as debugging information or editor-specific markup.
getImagePath
Returns the full URL path to an image file in the Magento media directory.
This method converts a relative media path (like catalog/image.jpg) into a full URL that can be used in <img> tags.
getResponsiveImageData
Prepares image data for generating responsive <picture> tags with multiple image sources.
This method processes a Hyvä CMS image field value and returns one <picture> source with width, height, srcset, and media-query attributes. The $type argument is a unique id used to track the generated images, so use your own value (for example vendor_component-name_type) in custom components.
Example usage for responsive images:
getLinkData
Processes Hyvä CMS link field configuration and returns structured link data.
This method takes link configuration from a link field and returns an array containing the URL, label, and open-in-new-tab settings. Use this method to safely render links from Hyvä CMS link fields.
Example usage for link fields:
$link = $block->getLinkData($block->getData('link') ?? []);
// Returns: ['url' => '...', 'label' => '...', 'open_in_new' => true/false]
buildClasses
Builds a string of CSS classes combining base classes with user-configured classes.
buildClasses(array $baseClasses, ?string $configKey = null, bool $includeElementClasses = true): string
This method merges CSS classes defined in your template with any additional classes specified by content editors in the Hyvä CMS component configuration. This allows editors to add custom styling without modifying the template.
Example usage for component CSS classes:
createChildHtml
Creates and renders child components without using parent-child layout relationships.
This method renders Hyvä CMS child components while avoiding layout conflicts. Use this method when your component accepts children to properly render nested component structures.
Example usage for child components:
renderRichText
Safely renders a richtext field's stored HTML, resolving Hyvä's own directives and standard Magento directives.
<?= /** @noEscape */ $block->renderEditorMessage([
'preview_message' => __('No image selected'),
'button_text' => __('Select Image'),
]) ?>
Processing runs in a defined order: the HTML is first escaped against a tag allow-list (common formatting tags plus wbr and img), then Hyva\CmsLiveviewEditor\Model\RichText\DirectiveProcessor replaces {{hyva_image}} and {{hyva_link}}, and finally Magento's standard CMS template filter resolves the remaining directives ({{config}}, {{customVar}}, {{var}}, {{trans}}, {{store}}, {{widget}}, {{media}}). The same method runs identically in the preview iframe and on the storefront. See Rich Text Editor and Variables for the merchant-facing editing experience.
Example usage in component template:
Content Security Policy (CSP) and JavaScript in Hyvä CMS Components
When adding JavaScript to Hyvä CMS component templates, follow these guidelines to ensure compatibility with Magento Content Security Policy (CSP) and the Hyvä CMS Liveview Editor.
CSP-Compatible Script Loading:
- Do not include inline
<script>tags directly in your Hyvä CMS component templates. - Add your JavaScript files before the closing
</body>tag using Magento's layout XML, referencing thebefore.body.endcontainer.
Example layout XML adding a script before </body>:
<?xml version="1.0"?>
<page
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"
>
<body>
<referenceContainer name="before.body.end">
<block
class="Magento\Framework\View\Element\Template"
name="vendor.my-component.script"
template="Vendor_Module::my-component/script.phtml"
/>
</referenceContainer>
</body>
</page>
This ensures your JavaScript is available both during initial page load and when the Hyvä CMS editor updates the preview content dynamically.
For the Alpine.js initialization pattern and full Content Security Policy configuration in Hyvä Themes, see the CSP and Magento documentation.
Extending the Rich Text Editor
The richtext field uses TipTap for editing. The instance is exposed through window.hyvaTiptapUtility, so third-party modules can register additional TipTap extensions before the editor initializes:
Rendering Block ID and CSS Classes in Templates
Most Hyvä CMS components should support custom CSS classes in their advanced section. The Hyva\CmsLiveviewEditor\Block\Element class provides a helper method to render the configured classes.
Example component template with CSS classes:
<?php
declare(strict_types=1);
use Hyva\CmsLiveviewEditor\Block\Element;
use Magento\Framework\Escaper;
/** @var Element $block */
/** @var Escaper $escaper */
?>
<div class="<?= $escaper->escapeHtmlAttr($block->getCssClasses()) ?>">
<!-- Component content goes here -->
</div>
The getCssClasses() method returns the CSS classes configured in the component's advanced section, so content editors can add custom styling without modifying the template.
The block id and the editor integration attributes are injected automatically into this first element (see Automatic Editor Attributes), so you do not need to call renderBlockId() or getEditorAttrs() here. If you opt out with $block->setData('auto_attributes', false), render them yourself:
<div
class="<?= $escaper->escapeHtmlAttr($block->getCssClasses()) ?>"
<?= /** @noEscape */ $block->renderBlockId() ?>
<?= /** @noEscape */ $block->getEditorAttrs() ?>
>
Rendering Responsive Images
To render responsive, optimized <picture> elements from a component's image fields, use the getResponsiveImageData() block helper together with the Hyva\Theme\ViewModel\Media view model. This serves appropriately sized images per viewport, and when the Media Optimization module is installed the sources are resized and converted automatically (it falls back to a plain <picture> when the module is not present).
For the full pattern, including a template example, art-directed variants, and choosing unique ids, see Media Optimization: Hyvä CMS Integration.
Processing Link Fields Consistently
Use the getLinkData() method to process Hyvä CMS link fields into a consistent data structure. This method handles URL generation, label extraction, and open-in-new-tab settings.
Example link field rendering:
<?php
declare(strict_types=1);
use Hyva\CmsLiveviewEditor\Block\Element;
use Magento\Framework\Escaper;
/** @var Element $block */
/** @var Escaper $escaper */
// Process link field data into structured array
// Returns: ['url' => '...', 'label' => '...', 'open_in_new' => true/false]
$link = $block->getLinkData($block->getData('link') ?? []);
?>
<a
href="<?= $escaper->escapeHtmlAttr($link['url']) ?>"
<?= $link['open_in_new'] ? 'target="_blank" rel="noopener"' : '' ?>
<?= /** @noEscape */ $block->getEditorAttrs() ?>
>
<?= $escaper->escapeHtml($link['label']) ?>
</a>
The getLinkData() method ensures consistent link handling across all Hyvä CMS components and properly resolves different link types (internal pages, external URLs, etc.).
Rendering Child Components
Use the createChildHtml() method to render Hyvä CMS child components within a parent component template. This method properly handles editor integration and avoids Magento layout conflicts.
Example child component rendering:
<?php
declare(strict_types=1);
use Hyva\CmsLiveviewEditor\Block\Element;
/** @var Element $block */
// Check if component has children
$hasChildren = $block->hasChildren();
$children = $block->getChildren();
?>
<div <?= /** @noEscape */ $block->getEditorAttrs() ?>>
<?php if ($hasChildren): ?>
<div class="child-container">
<?php foreach ($children ?: [] as $elementData): ?>
<?= $block->createChildHtml($elementData, 'child_prefix') ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
The createChildHtml() method renders each child component with proper editor attributes. The second parameter ('child_prefix') provides a unique prefix for child block names to avoid naming conflicts.
Reference Examples in Hyva_CmsBase Module
The Hyva_CmsBase module contains many example components demonstrating different features and patterns. Review these examples to learn advanced component techniques and see real-world implementations.
Browse the component templates in the Hyva_CmsBase module source code: Hyva_CmsBase component templates
These examples include components with variants, child components, responsive images, link handling, and advanced field configurations.