Dieser Viewhelper hilft dabei, nur spezifische Tags zu entfernen. Anders als der Core: StripTags Viewhelper, der alle Tags entfernt.
Viewhelper PHP Code
Binden Sie diesen Viewhelper mit dem Namen "StripSpecificTagsViewHelper.php" ein und fügen Sie den Code ein:
<?php
namespace LdoerrDotCom\Extname\ViewHelpers;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
/**
* Class StripSpecificTagsViewHelper
*
* Removes specific HTML tags (e.g., <p>) from a given string.
*
* Usage:
* <ld:stripSpecificTags variable="{html}" tags="p,span" />
*
* Declaration: xmlns:ld="http://typo3.org/ns/LdoerrDotCom/Extname/ViewHelpers"
*
* @package LdoerrDotCom\Extname\ViewHelpers
*/
class StripSpecificTagsViewHelper extends AbstractViewHelper
{
/**
* Do not escape the output (we return HTML).
*
* @var bool
*/
protected $escapeOutput = false;
/**
* Initialize arguments.
*/
public function initializeArguments(): void
{
$this->registerArgument('variable', 'string', 'The input HTML string', true);
$this->registerArgument('tags', 'string', 'Comma-separated list of tags to remove, e.g. "p,span"', true);
}
/**
* Removes specified tags from the string.
*
* @return string
*/
public function render(): string
{
$content = $this->arguments['variable'];
$tags = array_map('trim', explode(',', $this->arguments['tags']));
foreach ($tags as $tag) {
// Remove both opening and closing tags of the given tag
$content = preg_replace('#</?' . preg_quote($tag, '#') . '[^>]*>#i', '', $content);
}
return $content;
}
}
Anschließend kann der Viewhelper im Fluid Template eingesetzt werden:
<html xmlns:f="http://typo3.org/ns/TYPO3/Fluid/ViewHelpers"
xmlns:ld="http://typo3.org/ns/LdoerrDotCom/Extname/ViewHelpers"
data-namespace-typo3-fluid="true">
...
<h1><ld:stripSpecificTags variable="{data.header -> f:format.html()}" tags="p" /></h1>
Einsatzbeispiel: Man möchte gewisse Tags, wie Umbrüche (<br>) zulassen, aber das geht nur, wenn man die Fluid Variable mit "f:format.html" ausgibt. Dadurch wird aber automatisch auch ein "<p>"-Tag um den Inhalt gesetzt. Diesen kann man zwar mit f:format.stripTags entfernen (Core VH), allerdings werden dadurch auch alle anderen Tags (Der gewünschte "<br>" Tag z.B.) verloren. Mit diesem Viewhelper kann man sich auswählen, welche Tags entfernt werden sollen. Mit Komma kann man auch mehrere Tags eintragen.
Wie hier zum Beispiel:
<h2l:stripSpecificTags variable="{data.header -> f:format.html()}" tags="p,span,i" />