Table of Contents
Table of Content
How to create custom Fluid-ViewHelper for WordPress #
Create a file inside of your plugin located at Classes/ViewHelpers/{Name}ViewHelper.php
.
In this example we will create a ViewHelper to output a random number. The min
and max
value can be passed as arguments in the Fluid-Template of your Widget.
You will be able to use the ViewHelper with in the tag- or inline-syntax:
// Tag syntax
<ex:random min="1" max="10" />
// Inline syntax:
{ex:random(min:1, max:10)}
File: Classes/ViewHelpers/RandomViewHelper.php
#
<?php
namespace My\Example\ViewHelpers;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
class RandomViewHelper extends AbstractViewHelper
{
use CompileWithRenderStatic;
/**
* @var boolean
*/
protected $escapeChildren = false;
/**
* @var boolean
*/
protected $escapeOutput = false;
/**
* @return void
*/
public function initializeArguments() {
parent::initializeArguments();
$this->registerArgument('min', 'int', 'Minimum value');
$this->registerArgument('max', 'int', 'Maximum value');
}
/**
* @return int
*/
public static function renderStatic( array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext) {
return rand( $arguments['min'], $arguments['max'] );
}
}
Registering the namespace ex:
with fluid #
In order to use the ViewHelper we need to register the namespace. Inside of your Widget / Block-Controller this can be done inside of the initializeView()
method using $this->view->addViewHelperNameSpace()
:
File: Classes/Controller/Elementor/ExampleController.php
#
<?php
namespace My\Example\Controller\Elementor;
use Nng\Nnhelpers\Controller\AbstractElementorController;
class ExampleController extends AbstractElementorController
{
// ... skipped the properties here
public function initializeView( $view = null )
{
$this->view->addViewHelperNameSpace('ex', 'My\\Example\\ViewHelpers');
}
}
Using the ViewHelper inside of the Fluid Template #
Now we are going to use it in our Widget Template:
File: Resources/Templates/Elementor/Example.html
#
<h1>Your lucky number is {ex:random(min:1, max:13)}</h1>