T3SEO

TYPO3 and SEO since 2011

Write custom Fluid ViewHelpers I

Among the standard repertoire of ViewHelpers shipped with Fluid, that are directly usable, you are also able to develop your custom ViewHelpers. This can be done quicker and easier than you probably think.

Create ViewHelper Class

In Extbase and Fluid a lot of things work by naming conventions, and so there is a specific location where you have to put your ViewHelpers in order to use them in a Fluid template. Inside your extension's Classes folder create a Folder ViewHelpers.

The ViewHelpers' name has to end on "ViewHelper". In your new ViewHelpers folder create a PHP file with this name, e.g. ReverseViewHelper.php.

This PHP file has to contain a class named Tx_[YourExtension]_ViewHelpers_ReverseViewHelper:

<?php

class Tx_MyExt_ViewHelpers_ReverseViewHelper extends Tx_Fluid_Core_ViewHelper_AbstractViewHelper {

	/**
	 * Reverses the string
	 *
	 * @param string $string
	 * @return 
	 */
	public function render($string) {
		return strrev($string);
	}

}

?>

This is the minimum requirement for a self made ViewHelper:

  • The ViewHelper is a class that extends Tx_Fluid_Core_ViewHelper_AbstractViewHelper. (For special types of ViewHelpers Fluid also provides specific base classes, however they are also just extensions of this AbstractViewHelper.)
  • The render() method has to be implemented as it is calles when the ViewHelper is rendered.
  • Like so many times in Extbase and Fluid the render() method's DocComment is mandatory. All parameters and their datatypes of the ViewHelper have to be declared there.

Our ViewHelper is now ready to use:

Custom ViewHelper in use

{namespace m=Tx_MyExt_ViewHelpers}
<h2>Example usages</h2>
<ul>
    <li>
        Fluid is
        <m:reverse string="lufrewop" />
    </li>
    <li>
        Extbase is {m:reverse(string:'lufrewop')}
    </li>
</ul>
  • The first line is crucial, if you want to use custom ViewHelpers. Here a Fluid namespace is defined, which means that a namespace identifier is connected with a certain ViewHelper folder.
  • In this case I defined m as a namespace for the MyExt extension. Because of the naming conventions Fluid immediatelly knows where to include the ViewHelper class from. The namespace identifier can be chosen arbitrarily and can as well be longer than one character.
  • The ViewHelper can be used as a tag and as shorthand with curly brackets.

More to come

Shortly I want to release 2 or 3 more articles about custom built ViewHelpers, to explain more details and possibilities. So you're advised to subscribe the feed or be up to date on Twitter.

Write custom Fluid ViewHelpers I

    Related Topics

  • TYPO3