{
    "mode": "perldoc",
    "parameter": "Template::Manual::Views",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Template%3A%3AManual%3A%3AViews/json",
    "generated": "2026-07-05T13:37:48Z",
    "sections": {
        "NAME": {
            "content": "Template::Manual::Views - Template Toolkit views (experimental)\n",
            "subsections": []
        },
        "Overview": {
            "content": "A view is effectively a collection of templates and/or variable definitions which can be passed\naround as a self-contained unit. This then represents a particular interface or presentation\nstyle for other objects or items of data.\n\nYou can use views to implement custom \"skins\" for an application or content set. You can use\nthem to help simplify the presentation of common objects or data types. You can even use then to\nautomate the presentation of complex data structures such as that generated in an \"XML::DOM\"\ntree or similar. You let an iterator do the walking, and the view does the talking (or in this\ncase, the presenting). Voila - you have view independent, structure shy traversal using\ntemplates.\n\nIn general, views can be used in a number of different ways to achieve several different things.\nThey elegantly solve some problems which were otherwise difficult or complicated, and make easy\nsome things that were previously hard.\n\nAt the moment, they're still very experimental. The directive syntax and underlying API are\nlikely to change quite considerably over the next version or two. Please be very wary about\nbuilding your multi-million dollar e-commerce solutions based around this feature.\n",
            "subsections": []
        },
        "Views as Template Collectors/Providers": {
            "content": "The \"VIEW\" directive starts a view definition and includes a name by which the view can be\nreferenced. The view definition continues up to the matching \"END\" directive.\n\n[% VIEW myview %]\n...\n[% END %]\n\nThe first role of a view is to act as a collector and provider of templates. The \"include()\"\nmethod can be called on a view to effectively do the same thing as the \"INCLUDE\" directive. The\ntemplate name is passed as the first argument, followed by any local variable definitions for\nthe template.\n\n[% myview.include('header', title='The Title') %]\n\n# equivalent to\n[% INCLUDE header  title='The Title' %]\n\nViews accept a number of configuration options which can be used to control different aspects of\ntheir behaviour. The '\"prefix\"' and '\"suffix\"' options can be specified to add a fixed prefix\nand/or suffix to the name of each template.\n\n[% VIEW myview\nprefix = 'my/'\nsuffix = '.tt2' ;\nEND\n%]\n\nNow the call\n\n[% myview.include('header', title='The Title') %]\n\nis equivalent to\n\n[% INCLUDE my/header.tt2  title='The Title' %]\n\nViews provide an \"AUTOLOAD\" method which maps method names to the \"include()\" method. Thus, the\nfollowing are all equivalent:\n\n[% myview.include('header', title='Hello World') %]\n[% myview.includeheader(title='Hello World') %]\n[% myview.header(title='Hello World') %]\n",
            "subsections": []
        },
        "Local BLOCK Definitions": {
            "content": "A \"VIEW\" definition can include \"BLOCK\" definitions which remain local to the view. A request\nfor a particular template will return a \"BLOCK\", if defined, in preference to any other template\nof the same name.\n\n[% BLOCK foo %]\npublic foo block\n[% END %]\n\n[% VIEW plain %]\n[% BLOCK foo %]\nplain foo block\n[% END %]\n[% END %]\n\n[% VIEW fancy %]\n[% BLOCK foo %]\nfancy foo block\n[% END %]\n[% END %]\n\n[% INCLUDE foo %]       # public foo block\n[% plain.foo %]         # plain foo block\n[% fancy.foo %]         # fancy foo block\n\nIn addition to \"BLOCK\" definitions, a \"VIEW\" can contain any other template directives. The\nentire \"VIEW\" definition block is processed to initialise the view but no output is generated\n(this may change RSN - and get stored as '\"output\"' item, subsequently accessible as \"[%\nview.output %]\"). However, directives that have side-effects, such as those that update a\nvariable, will have noticeable consequences.\n",
            "subsections": []
        },
        "Preserving Variable State within Views": {
            "content": "Views can also be used to save the values of any existing variables, or to create new ones at\nthe point at which the view is defined. Unlike simple template metadata (\"META\") which can only\ncontain static string values, the view initialisation block can contain any template directives\nand generate any kind of dynamic output and/or data items.\n\n[% VIEW mywebsite %]\n[% view.title   = title or 'My Cool Web Site' %]\n[% view.author  = \"$abw.name, $abw.email\" %]\n[% view.sidebar = INCLUDE my/sidebar.tt2 %]\n[% END %]\n\nNote that additional data items can be specified as arguments to the \"VIEW\" directive. Anything\nthat doesn't look like a configuration parameter is assumed to be a data item. This can be a\nlittle hazardous, of course, because you never know when a new configuration item might get\nadded which interferes with your data.\n\n[% VIEW mywebsite\n# config options\nprefix = 'my/'\n# misc data\ntitle   = title or 'My Cool Web Site'\nauthor  = \"$abw.name, $abw.email\"\nsidebar = INCLUDE my/sidebar.tt2\n%]\n...\n[% END %]\n\nOutside of the view definition you can access the view variables as, for example:\n\n[% mywebsite.title %]\n\nOne important feature is the equivalence of simple variables and templates. You can implement\nthe view item '\"title\"' as a simple variable, a template defined in an external file, possibly\nwith a prefix/suffix automatically appended, or as a local \"BLOCK\" definition within the \"[%\nVIEW %] ... [% END %]\" definition. If you use the syntax above then the view will Do The Right\nThing to return the appropriate output.\n\nAt the \"END\" of the \"VIEW\" definition the view is \"sealed\" to prevent you from accidentally\nupdating any variable values. If you attempt to change the value of a variable after the \"END\"\nof the \"VIEW\" definition block then a \"view\" error will be thrown.\n\n[% TRY;\nmywebsite.title = 'New Title';\nCATCH;\nerror;\nEND\n%]\n\nThe error above will be reported as:\n\nview error - cannot update item in sealed view: title\n\nThe same is true if you pass a parameter to a view variable. This is interpreted as an attempt\nto update the variable and will raise the same warning.\n\n[% mywebsite.title('New Title') %]    # view error!\n\nYou can set the \"silent\" parameter to have the view ignore these parameters and simply return\nthe variable value.\n\n[% VIEW mywebsite\nsilent = 1\ntitle  = title or 'My Cool Web Site'\n# ... ;\nEND\n%]\n\n[% mywebsite.title('Blah Blah') %]   # My Cool Web Site\n\nAlternately, you can specify that a view is unsealed allowing existing variables to be updated\nand new variables defined.\n\n[% VIEW mywebsite\nsealed = 0\ntitle  = title or 'My Cool Web Site'\n# ... ;\nEND\n%]\n\n[% mywebsite.title('Blah Blah') %]   # Blah Blah\n[% mywebsite.title %]                # Blah Blah\n",
            "subsections": [
                {
                    "name": "Inheritance, Delegation and Reuse",
                    "content": "Views can be inherited from previously defined views by use of the \"base\" parameter. This\nexample shows how a base class view is defined which applies a \"view/default/\" prefix to all\ntemplate names.\n\n[% VIEW my.view.default\nprefix = 'view/default/';\nEND\n%]\n\nThus the directive:\n\n[% my.view.default.header(title='Hello World') %]\n\nis now equivalent to:\n\n[% INCLUDE view/default/header title='Hello World' %]\n\nA second view can be defined which specifies the default view as a base.\n\n[% VIEW my.view.fancy\nbase   = my.view.default\nprefix = 'view/fancy/';\nEND\n%]\n\nNow the directive:\n\n[% my.view.fancy.header(title='Hello World') %]\n\nwill resolve to:\n\n[% INCLUDE view/fancy/header title='Hello World' %]\n\nor if that doesn't exist, it will be handled by the base view as:\n\n[% INCLUDE view/default/header title='Hello World' %]\n\nWhen a parent view is specified via the \"base\" parameter, the delegation of a view to its parent\nfor fetching templates and accessing user defined variables is automatic. You can also implement\nyour own inheritance, delegation or other reuse patterns by explicitly delegating to other\nviews.\n\n[% BLOCK foo %]\npublic foo block\n[% END %]\n\n[% VIEW plain %]\n[% BLOCK foo %]\n<plain>[% PROCESS foo %]</plain>\n[% END %]\n[% END %]\n\n[% VIEW fancy %]\n[% BLOCK foo %]\n[% plain.foo | replace('plain', 'fancy') %]\n[% END %]\n[% END %]\n\n[% plain.foo %]     # <plain>public foo block</plain>\n[% fancy.foo %]     # <fancy>public foo block</fancy>\n\nNote that the regular \"INCLUDE/PROCESS/WRAPPER\" directives work entirely independently of views\nand will always get the original, unaltered template name rather than any local per-view\ndefinition.\n"
                },
                {
                    "name": "Self-Reference",
                    "content": "A reference to the view object under definition is available with the \"VIEW ... END\" block by\nits specified name and also by the special name '\"view\"' (similar to the \"my $self = shift;\" in\na Perl method or the '\"this\"' pointer in C++, etc). The view is initially unsealed allowing any\ndata items to be defined and updated within the \"VIEW ... END\" block. The view is automatically\nsealed at the end of the definition block, preventing any view data from being subsequently\nchanged.\n\n(NOTE: sealing should be optional. As well as sealing a view to prevent updates (\"SEALED\"), it\nshould be possible to set an option in the view to allow external contexts to update existing\nvariables (\"UPDATE\") or even create totally new view variables (\"CREATE\")).\n\n[% VIEW fancy %]\n[% fancy.title  = 'My Fancy Title' %]\n[% fancy.author = 'Frank Open' %]\n[% fancy.col    = { bg => '#ffffff', bar => '#a0a0ff' } %]\n[% END %]\n\nor\n\n[% VIEW fancy %]\n[% view.title  = 'My Fancy Title' %]\n[% view.author = 'Frank Open' %]\n[% view.col    = { bg => '#ffffff', bar => '#a0a0ff' } %]\n[% END %]\n\nIt makes no real difference in this case if you refer to the view by its name, '\"fancy\"', or by\nthe general name, '\"view\"'. Outside of the view block, however, you should always use the given\nname, '\"fancy\"':\n\n[% fancy.title  %]\n[% fancy.author %]\n[% fancy.col.bg %]\n\nThe choice of given name or '\"view\"' is much more important when it comes to \"BLOCK\" definitions\nwithin a \"VIEW\". It is generally recommended that you use '\"view\"' inside a \"VIEW\" definition\nbecause this is guaranteed to be correctly defined at any point in the future when the block\ngets called. The original name of the view might have long since been changed or reused but the\nself-reference via '\"view\"' should always be intact and valid.\n\nTake the following VIEW as an example:\n\n[% VIEW foo %]\n[% view.title = 'Hello World' %]\n[% BLOCK header %]\nTitle: [% view.title %]\n[% END %]\n[% END %]\n\nEven if we rename the view, or create a new \"foo\" variable, the header block still correctly\naccesses the \"title\" attribute of the view to which it belongs. Whenever a view \"BLOCK\" is\nprocessed, the \"view\" variable is always updated to contain the correct reference to the view\nobject to which it belongs.\n\n[% bar = foo %]\n[% foo = { title => \"New Foo\" } %]  # no problem\n[% bar.header %]                    # => Title: Hello World\n"
                },
                {
                    "name": "Saving References to External Views",
                    "content": "When it comes to view inheritance, it's always a good idea to take a local copy of a parent or\ndelegate view and store it as an attribute within the view for later use. This ensures that the\ncorrect view reference is always available, even if the external name of a view has been\nchanged.\n\n[% VIEW plain %]\n...\n[% END %]\n\n[% VIEW fancy %]\n[% view.plain = plain %]\n[% BLOCK foo %]\n[% view.plain.foo | replace('plain', 'fancy') %]\n[% END %]\n[% END %]\n\n[% plain.foo %]         # => <plain>public foo block</plain>\n[% plain = 'blah' %]    # no problem\n[% fancy.foo %]         # => <fancy>public foo block</fancy>\n"
                },
                {
                    "name": "Views as Data Presenters",
                    "content": "Another key role of a view is to act as a dispatcher to automatically apply the correct template\nto present a particular object or data item. This is handled via the \"print()\" method.\n\nHere's an example:\n\n[% VIEW foo %]\n\n[% BLOCK text %]\nSome text: [% item %]\n[% END %]\n\n[% BLOCK hash %]\na hash:\n[% FOREACH key = item.keys.sort -%]\n[% key %] => [% item.$key %]\n[% END -%]\n[% END %]\n\n[% BLOCK list %]\na list: [% item.sort.join(', ') %]\n[% END %]\n\n[% END %]\n\nWe can now use the view to print text, hashes or lists. The \"print()\" method includes the right\ntemplate depending on the typing of the argument (or arguments) passed.\n\n[% sometext = 'I read the news today, oh boy.' %]\n[% ahash    = { house => 'Lords', hall => 'Albert' } %]\n[% alist    = [ 'sure', 'Nobody', 'really' ] %]\n\n[% view.print(sometext) %]\n# Some text: I read the news today, oh boy.\n\n[% view.print(ahash) %]\n# a hash:\nhall => Albert\nhouse => Lords\n[% view.print(alist) %]\n# a list: Nobody, really, sure\n\nYou can also provide templates to print objects of any other class. The class name is mapped to\na template name with all non-word character sequences such as '\"::\"' converted to a single\n'\"\"'.\n\n[% VIEW foo %]\n[% BLOCK FooBar %]\na Foo::Bar object:\nthingies: [% view.print(item.thingies) %]\ndoodahs: [% view.print(item.doodahs)  %]\n[% END %]\n[% END %]\n\n[% USE fubar = Foo::Bar(...) %]\n\n[% foo.print(fubar) %]\n\nNote how we use the view object to display various items within the objects ('\"thingies\"' and\n'\"doodahs\"'). We don't need to worry what kind of data these represent (text, list, hash, etc)\nbecause we can let the view worry about it, automatically mapping the data type to the correct\ntemplate.\n\nViews may define their own type => template map.\n\n[% VIEW foo\nmap = { TEXT  => 'plaintext',\nARRAY => 'showlist',\nHASH  => 'showhash',\nMy::Module => 'templatename'\ndefault    => 'anyolddata'\n}\n%]\n[% BLOCK plaintext %]\n...\n[% END %]\n\n...\n[% END %]\n\nThey can also provide a \"default\" map entry, specified as part of the \"map\" hash or as a\nparameter by itself.\n\n[% VIEW foo\nmap     = { ... },\ndefault = 'whatever'\n%]\n...\n[% END %]\n\nor\n\n[% VIEW foo %]\n[% view.map     = { ... }\nview.default = 'whatever'\n%]\n...\n[% END %]\n\nThe \"print()\" method provides one more piece of magic. If you pass it a reference to an object\nwhich provides a \"present()\" method, then the method will be called passing the view as an\nargument. This then gives any object a chance to determine how it should be presented via the\nview.\n\npackage Foo::Bar;\n...\nsub present {\nmy ($self, $view) = @;\nreturn \"a Foo::Bar object:\\n\"\n. \"thingies: \" . $view->print($self->{ THINGIES }) . \"\\n\"\n. \"doodahs: \" . $view->print($self->{ DOODAHS }) . \"\\n\";\n}\n\nThe object is free to delve deeply into its innards and mess around with its own private data,\nbefore presenting the relevant data via the view. In a more complex example, a \"present()\"\nmethod might walk part of a tree making calls back against the view to present different nodes\nwithin the tree. We may not want to expose the internal structure of the tree (because that\nwould break encapsulation and make our presentation code dependant on it) but we want to have\nsome way of walking the tree and presenting items found in a particular manner.\n\nThis is known as *Structure Shy Traversal*. Our view object doesn't require prior knowledge\nabout the internal structure of any data set to be able to traverse it and present the data\ncontained therein. The data items themselves, via the \"present()\" method, can implement the\ninternal iterators to guide the view along the right path to presentation happiness.\n\nThe upshot is that you can use views to greatly simplify the display of data structures like\n\"XML::DOM\" trees. The documentation for the \"Template::Plugin::XML::DOM\" module contains an\nexample of this. In essence, it looks something like this:\n\nXML source:\n\n<user name=\"Andy Wardley\">\n<project id=\"iCan\" title=\"iCan, but theyCan't\"/>\n<project id=\"p45\"  title=\"iDid, but theyDidn't\"/>\n</user>\n\nTT View:\n\n[% VIEW fancy %]\n[% BLOCK user %]\nUser: [% item.name %]\n[% item.content(myview) %]\n[% END %]\n\n[% BLOCK project %]\nProject: [% project.id %] - [% project.name %]\n[% END %]\n[% END %]\n\nGenerate view:\n\n[% USE dom = XML.DOM %]\n[% fancy.print(dom.parse(xmlsource)) %]\n\nOutput:\n\nUser: Andy Wardley\nProject: iCan - iCan, but theyCan't\nProject: p45 - iDid, but theyDidn't\n\nThe same approach can be applied to many other areas. Here's an example from the\n\"File\"/\"Directory\" plugins.\n\n[% VIEW myview %]\n[% BLOCK file %]\n- [% item.name %]\n[% END %]\n\n[% BLOCK directory %]\n* [% item.name %]\n[% item.content(myview) FILTER indent %]\n[% END %]\n[% END %]\n\n[% USE dir = Directory(dirpath) %]\n[% myview.print(dir) %]\n\nAnd here's the same approach use to convert POD documentation to any other format via template.\n\n[%  # load Pod plugin and parse source file into Pod Object Model\nUSE Pod;\npom = Pod.parsefile(mypodfile);\n\n# define view to map all Pod elements to \"pod/html/xxx\" templates\nVIEW pod2html\nprefix='pod/html';\nEND;\n\n# now print document via view (i.e. as HTML)\npod2html.print(pom)\n%]\n\nHere we simply define a template prefix for the view which causes the view to look for\n\"pod/html/head1\", \"pod/html/head2\", \"pod/html/over\" as templates to present the different\nsections of the parsed Pod document.\n\nThere are some examples in the Template Toolkit test suite: t/pod.t and t/view.t which may shed\nsome more light on this. See the distribution sub-directory examples/pod/html for examples of\nPod -> HTML templates.\n"
                }
            ]
        }
    },
    "summary": "Template::Manual::Views - Template Toolkit views (experimental)",
    "flags": [],
    "examples": [],
    "see_also": []
}