[FR] Add BEFORE_RENDER_ELEMENT event to ElementHelper #17188
-
I would like to override the Something like: if (Event::hasHandlers(static::class, self::EVENT_BEFORE_RENDER_ELEMENT)) {
$output = null;
$event = new BeforeRenderElementEvent([
'element' => $element,
'variables' => $variables,
'templates' => $templates,
'output' => $output,
]);
Event::trigger(static::class, self::EVENT_BEFORE_RENDER_ELEMENT, $event);
return $event->output;
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
I moved the rendering logic over to use craft\base\Element;
use craft\events\RenderElementEvent;
use yii\base\Event;
Event::on(Element::class, Element::EVENT_RENDER, function(RenderElementEvent $event) {
/** @var Element $element */
$element = $event->sender;
$event->output = '…';
}); |
Beta Was this translation helpful? Give feedback.
-
@brandonkelly I've implemented this locally and it works as I hoped. One possible improvement… Can the event fire after the template path logic and send the templates through to the event? The only downside of this is that a developer may want to render an element that doesn't have a My implementation looks like this: public function transform(Element $element): ?UxComponentInterface
{
$refHandle = $element::refHandle();
if ($refHandle === null) {
throw new NotSupportedException(sprintf('Element type “%s” doesn’t define a reference handle, so it doesn’t support ux components.', $element::displayName()));
}
$generalConfig = Craft::$app->getConfig()->getGeneral();
$componentNameParts = explode(DIRECTORY_SEPARATOR, $generalConfig->partialTemplatesPath);
$componentNameParts[] = $refHandle;
$handle = $element->getFieldLayout()?->provider?->getHandle();
if ($handle) {
$componentNameParts[] = $handle;
}
$templatePath = implode(DIRECTORY_SEPARATOR, $componentNameParts);
$componentNameParts[] = ucfirst(end($componentNameParts));
$className = "templates\\".implode("\\", $componentNameParts);
// Create a class with the block handle
if (class_exists($className)) {
$config = [
'__class' => $className,
$refHandle => $element,
'templatePath' => $templatePath
];
return Craft::createObject($config);
}
return null;
} You can see I'm repeating a lot of the same code to determine the |
Beta Was this translation helpful? Give feedback.
-
@brandonkelly Also regarding these lines: https://github.com/craftcms/cms/blob/5.8/src/base/Element.php#L6855-L6864 I think these are redundant from my testing. These lines: https://github.com/craftcms/cms/blob/5.8/src/base/Element.php#L6866-L6869 Seem to apply the entryType for entries to the template paths. That said I don't fully understand |
Beta Was this translation helpful? Give feedback.
I moved the rendering logic over to
Element::render()
and added anEVENT_RENDER
event from there, for Craft 5.8: (013f83c)