stmllr.net

Writing a basic Fluid ViewHelper for TYPO3

by on stmllr.net

After listening to Sebastians talk at T3DD09 today about the new templating engine Fluid, I felt inspired to give it a try. I am really surprised how easy it is to extend Fluid by writing an own ViewHelper. Read on to learn how to get started.

My goal was to add a Fluid ViewHelper to the blog_example extension. This extension is backported from FLOW3 to TYPO3 v.4 as a demonstration for extBase. Read more about blog_example, extBase and Fluid in v.4 in the MVC framework project page. I will not explain details here but concentrate on the view helper stuff. My view helper should add a new template marker which creates a dummy text "Lorem Ipsum". The marker expects an integer value, which is used for cropping the dummy text.

After installing and setting up extBase, Fluid and the blog_example extensions, I added a new view helper folder in the blog_example extension:

mkdir typo3conf/ext/blog_example/Classes/ViewHelpers

This folder is generally used as a container for view helpers which are shipped with extensions. In the next step, I created a new which contains the helper itself:

touch typo3conf/ext/blog_example/Classes/ViewHelpers/LoremIpsumViewHelper.php

It's important to stick to this naming scheme, because otherwise Fluid will not find the view helper. Let's have a closer look at it. Beside the .php extension at the end of the filename, it contains two main parts: LoremIpsum and ViewHelper. LoremIpsum is the very name of the view helper and ViewHelper is a constant which is a mandatory part. The filename reflects the naming scheme of the class name of the view helper. So let's see what the file content looks like. I removed some comments to increase readability:

<?php

/**
 * This class is a demo view helper for the Fluid templating engine.
 *
 * @package TYPO3
 * @subpackage Fluid
 * @version
 */
class Tx_BlogExample_ViewHelpers_LoremIpsumViewHelper extends Tx_Fluid_Core_ViewHelper_AbstractViewHelper {

    /**
     * Renders some classic dummy content: Lorem Ipsum...
     *
     * @param int $length The number of characters of the dummy content
     * @validate $length IntegerValidator
     * @return string dummy content, cropped after the given number of characters
     * @author Lorem Ipsum <lorem@example.com>
     */
    public function render($length) {
        $dummyContent = 'Lorem ipsum dolor sit amet.';
        return substr($dummyContent, 0, $length);
    }
}

?>

This is a very basic example. My class extends the abstract view helper class of Fluid. I will not explain the Fluid API here. Let's concentrate on the example. The only method of my class is render() which is used to render the content of my marker. It crops a "Lorem Ipsum" string to a given length by using the substr() function. Some PHPDoc parts in the comments of the render() method are mandatory to get the view helper working. For example the @param part defines the argument and its type (int). Other PHPDoc parts are optional, like @validate. This argument ensures that the render() method only gets integer values. The validation itself is performed by the Extbase framework, so you don't have to care. If you'd like to learn more about validators, have a look at the PHP files in extbase/Classes/Validation/Validator/. That's all for this part of fluid.

In a next step, I've added the view helper to the Fluid template of blog_example:

# vi typo3conf/ext/blog_example/Resources/Private/Templates/Blog/index.html

First I had to declare a namespace for my view helpers. I do this at the top of the template file. I chose to use blog, to be used as a shortcut to all the view helpers of the blog_example extension. Next is the marker itself. I put the marker below the existing <f:layout> and <f:section> tags. The syntax of my new marker is easy to spot: The namespace and the viewhelper name is seperated by a : The length arguments is given afterwards:

{namespace blog=Tx_BlogExample_ViewHelpers} 

<f:layout name="default" />
<f:section name="content"> <h1>
  <blog:loremIpsum length="5" />
</h1>
</f:section>

The result of using this template marker is a level 1 header with "Lorem" as the text:

<h1>Lorem</h1>

That's all. I am really exited about how easy it is to write own view helpers. I hope this article could demonstrate that and motivate you to get into the FLOW3/Fluid/extBase universe.

Tags

Comments

  1. Steffen

    Please note that the code examples are all based on a unstable API, which is still under heavy developement.
    The blog post only wants to give an impression, how thing basically work. Chances are 99,9% that the code examples do not work with other versions of Fluid and Extbase than the one of May,16th 2009.
    Please be patient until the release of TYPO3 4.3, which will ship not only a stable API but also an up-to-date quickstarter tutorial.

  2. Elías

    Very didactical example.
    Now, I understand ViewHelpers.

  3. Steffen

    I have just updated the code examples to fit the 4.3 stable API. Have fun trying it out!

  4. rvt

    Why are viewhelpers not created in fileadmin?

  5. Steffen

    Well, TYPO3 expects viewhelpers to be found in a special directory (ext_name/Classes/ViewHelpers/). This way it can automatically scan the directory for viewhelpers and use them. No explicit registration needed, no hassle with including classes.

  6. superjens

    Very fine, thank you for let me understanding the ViewHelpers!

  7. milan

    Wonderful, thank you

  8. Till

    Thanks for this good article. Though, just as a hint in case you haven't noticed, $lenght != $length.

  9. Steffen

    haha, thanks for spotting this one, Till. This is one of my favorite typos. At least I used lenght consequently :)
    I have corrected the code examples and changed lenght to length.

  10. Roxanne

    <f:section name="content">

    should it not be

    <f:section name="content"/>

  11. Steffen

    Thx Roxanne for your hint. Almost correct. The closing tag was missing. I fixed it in the article

  12. Gilas

    Hi thank you for this article.
    It is not easy to understand fluid because there is several folders, piece of code, etc.
    I tried it and it works correctly,
    however when I edited

    # vi typo3conf/ext/blog_example/Resources/Private/Templates/Blog/index.html

    adding your code at the end of the template I got some erros for duplicating variables.

    So I replaced all the content with your code and all works fine.

    Now I need to do a new step: restore the previous Index.html (this is not a problem) instead I put your code in a new file:

    blog_example/Resources/Private/Templates/Blog/LoremIpsum.html

    now I want to do a new action to run this template.

    Hope you can write something and this could be userful to 'extend' this nice article.

    thank you

  13. Gilas

    to be more precise this is the error -- it is displayed and no matter if your code is before/after the existing template named 'default':

    Duplicate variable declarations!

    More information regarding this error might be available online.

    another tip: please add that each time you modify a file you should clear the configuration cache, otherwise the modifications are not applied.

Add a comment

Comments are moderated and need to approved. Please be patient.