What is the difference between render() and renderStatic() and what should be used when writing a ViewHelper in TYPO3
Asked Answered
M

1

8

There are several examples for writing a custom ViewHelper and different ways to do things. I have seen examples with render() and with renderStatic (for example in Developing a Custom ViewHelper).

In 24 Fluid Tips there is an explanation, but I don't understand it and it does not make it clear for me why there are 2 functions and what should be used where.

Breaking changes (Render method arguments on ViewHelpers deprecated) and fragmented information in various places makes it difficult to get a clear answer here. Is the example in Developing a Custom ViewHelper up to date and best practice?

Mezzotint answered 5/2, 2019 at 9:25 Comment(0)
P
15

renderStatic()
First of all, renderStatic() is a static PHP method. This means, you do not have access to instance attributes, such as $this->tag, which is for example required when your ViewHelper class is a subclass of AbstractTagBasedViewHelper.

Another drawback of renderStatic() is that you can not access child nodes. A child node is for example <f:then> in the following example:

<f:if condition="{variable}">
<f:then>
...
</f:then>
</f:if>

Having said that, renderStatic() features the best performance, because it is called from within compiled Fluid. Therefore, this method should be used if possible.

render()
Under certain circumstances, this method is the better choice or has to be used for a specific use case (see explanations above). The logic implemented in a render() method is not compiled, which has an impact on output that is cached.

The downside of render() is its performance.

Summary / Additional Notes

  • Use renderStatic(), if you can (performance).
  • Use render(), if you implement an TagBased-ViewHelper (subclass of
    TYPO3Fluid\Fluid\Core\ViewHelper\AbstractTagBasedViewHelper).
  • Use render(), if you need to read child nodes.
  • Review the ViewHelpers that are shipped with Fluid (e.g. TYPO3 v9 LTS) as examples.
    (see: typo3/sysext/fluid/Classes/ViewHelpers/*) [GitHub]
Paragraphia answered 5/2, 2019 at 23:40 Comment(2)
This is a brilliant answer! Thanks.Mezzotint
@Michael, Nice to have you on stackoverflow, Hope you remember.Collettecolletti

© 2022 - 2024 — McMap. All rights reserved.