Skip to content

Instantly share code, notes, and snippets.

@TommyKolkman
Last active April 13, 2016 10:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TommyKolkman/3cfba2c991ebaba0b0f6 to your computer and use it in GitHub Desktop.
Save TommyKolkman/3cfba2c991ebaba0b0f6 to your computer and use it in GitHub Desktop.
Observer to strip <p> tags for Magento 2
<?php
namespace Elephant\CFParent\Helper;
class ElephantData extends \Magento\Framework\App\Helper\AbstractHelper
{
public function __construct(
\Magento\Framework\App\Helper\Context $context,
array $data = []
) {
/**
* Data for further use in the widgets is collected here and can be instanced by injecting it in the child widget
* Example: \Elephant\CFParent\Helper\ElephantData $elephantData
**/
parent::__construct( $context, $data );
}
public function processContent($content)
{
// Remove wrapping paragraphs around widgets:
$content = preg_replace('/\<p\>{{(.*?)}}\<\/p\>/', '{{$1}}', $content);
// Remove div around widgets
$content = preg_replace('/\<div\>{{(.*?)}}\<\/div\>/', '{{$1}}', $content);
// Remove empty paragraphs:
$content = preg_replace('/<p>(|\s*|&nbsp;|\n)<\/p>/', '', $content);
return $content;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/Event/etc/events.xsd">
<event name="cms_page_render">
<observer name="elephant_cfparent_controller_cms_page_render" instance="Elephant\CFParent\Model\Observer" />
</event>
</config>
<?php
namespace Elephant\CFParent\Model;
use Magento\Framework\Event\ObserverInterface;
class Observer implements ObserverInterface {
/**
* @param Item $item
*/
public function __construct(
\Elephant\CFParent\Helper\ElephantData $elephantData
) {
$this->_elephantData = $elephantData;
}
/**
* @override
* @see ObserverInterface::execute()
* @used-by \Magento\Framework\Event\Invoker\InvokerDefault::_callObserverMethod()
* @see \Magento\Framework\App\Action\Action::dispatch()
*/
public function execute(\Magento\Framework\Event\Observer $observer) {
$page = $observer->getPage();
$content = $page->getContent();
$content = $this->_elephantData->processContent( $content );
$page->setContent($content);
}
}
@TommyKolkman
Copy link
Author

Giel Berkers forked this and made it compliant with having widgets in blocks too: https://gist.github.com/kanduvisla/d010b36639f79641bb76. If you stumble across this, use that one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment