2.9. Writing your own taglibs

Writing taglibs is straighforward, it is important to understand and remember the difference between taglibs and function taglibs. Function taglibs are PHP functions that are wrapped in a class and accessed under a common taglibs prefix. These functions can be called in the expression language.

Plain taglibs are also PHP function wrapped in a PHP class, each function defines a new tag that can be used in your document. The function gets called anytime the parser encounters the corresponding tag in the document. This means that for a bodyless tag the function is called only once, for tags with body it is instead called twice: once when the tag is open and once when it is closed.

To write a taglib you need to do the following:

The next example shows the implementation of a taglib that defines a bodyless tag and a tag with body. In the example, the bodyless tag requires one attribute and can only be used inside the tag with body.

Taglibs can be imported in two ways:

If you are going to use the taglib in only a few pages then choose the second option, as the taglib engine performs faster when less taglibs are included. The example below shows how to import the example taglibs shown in the previous paragraphs in a page:

After the taglibs have been imported in a page, the tags can be used in all its internal widgets.

The next example shows how to use the taglibs defined above in a widget:

Note

Always remember that, as described in Caches, the taglibs engine caches pages. This means that if you change the implementation of the taglibs but the code of the widgets using them is unchanged then you need to purge the taglibs cache in order to see the changes.