Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Filters

One of the problems with templates is that you can never be completely sure what content will be produced at the end. This is particularly true if you are pulling in some of your data from an external source. Perhaps you are producing an HTML page from news stories that have been entered into a database by reporters. You can’t be sure the stories don’t contain characters such as < or & that should be plain text but will be interpreted as HTML. Or perhaps you have room for only a certain number of characters and you don’t know how long a story will be.

The Template Toolkit provides filters to deal with these cases. A filter can be applied to part of a template and will postprocess those parts in a defined manner. For example, the html filter converts troublesome characters to their equivalent HTML entities, and the truncate filter will truncate text to a given length.

The FILTER directive introduces a filter, which operates on a block:

[% FILTER html %]
   HTML text may have < and > characters embedded
   that you want converted to the correct HTML entities.
[% END %]

The previous example produces the following output:

HTML text may have &lt; and &gt; characters embedded
that you want converted to the correct HTML entities.

The FILTER directive can also follow various other nonblock directives. For example:

[% INCLUDE mytext FILTER html %]

The | character can also be used as an alias for FILTER:

[% INCLUDE mytext | html %]

Multiple filters can be chained together and will be called in sequence:

[% INCLUDE mytext FILTER html FILTER html_para %]

or:

[% INCLUDE mytext | html | html_para %]

A number of standard filters are provided with the Template Toolkit; these are detailed in Chapter 5.

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint