简体   繁体   中英

How to call a TYPO3 custom viewhelper from a typoscript (.ts) file and receive a response from viewhelper?

I tried to call a custom viewhelper in TYPO3 9.5.9 from a typoscript file. But it is not working. An example for viewhelper is given below:

<?php
namespace MyVendor\BlogExample\ViewHelpers;

use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class GravatarViewHelper extends AbstractViewHelper
{
   use CompileWithRenderStatic;

   public static function renderStatic(
       array $arguments,
       \Closure $renderChildrenClosure,
       RenderingContextInterface $renderingContext
   ) {
       return 'World';
   }
}

How can I call this custom viewhelper from a typoscript (.ts) file and get a response?

I would suggest you extract the function that "does what the ViewHelper does" to a separate method and make it possible to call this method as a public method, and make it receive the PHP function arguments it requires (user email address, for example) *wrapped in an array $parameters .

This method can then be called from the ViewHelper as well as from TypoScript. The TypoScript would be something like:

lib.myGravatarObject = USER
lib.myGravatarObject.userFunc = MyVendor\ExtensionName\GravatarRenderer
lib.myGravatarObject.userEmail = foo@bar.com

If you name the properties of the array $parameters the same as your ViewHelper arguments you can simply pass $this->arguments or $arguments from within the ViewHelper (the former if you are implementing render() , the latter if you are implementing renderStatic() ). It also makes it more transparent that you use the same property names in TS as you would use for ViewHelper arguments.

You can use a FLUIDTEMPLATE cObject with a minimal template (eg via template property):

10 = FLUIDTEMPLATE
10 {
   template.cObject = TEXT
   template.cObject.value(
      <html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" xmlns:mv="http://typo3.org/ns/MyVendor/BlogExample/ViewHelpers" data-namespace-typo3-fluid="true">
      <mv:GravatarViewHelper />
   )
}

It seems to be possible. But as Bernd already asked: Why would one do that?

Why should you do this? (please describe your use case)

Viewhelpers are for usage in FLUID templates, there you have the correct and matching context.

If you want to call a PHP function inside of typoscript directly you have the option of an userfunc ( manual ). But you need to provide the necssary context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM