{
    "content": [
        {
            "type": "text",
            "text": "# HTML::Mason::Devel (perldoc)\n\n## NAME\n\nHTML::Mason::Devel - Mason Developer's Manual\n\n## DESCRIPTION\n\nThis manual is written for content developers who know HTML and at least a little Perl. The goal\nis to write, run, and debug Mason components.\n\n## Sections\n\n- **NAME**\n- **DESCRIPTION**\n- **HOW TO USE THIS MANUAL**\n- **IN-LINE PERL SECTIONS** (1 subsections)\n- **MASON OBJECTS** (3 subsections)\n- **CALLING COMPONENTS** (5 subsections)\n- **TOP-LEVEL COMPONENTS**\n- **PASSING PARAMETERS** (4 subsections)\n- **INITIALIZATION AND CLEANUP**\n- **EMBEDDED COMPONENTS**\n- **FLAGS AND ATTRIBUTES**\n- **FILTERING**\n- **COMMENT MARKERS**\n- **OTHER SYNTAX** (2 subsections)\n- **DATA CACHING** (9 subsections)\n- **WEB-SPECIFIC FEATURES** (4 subsections)\n- **USING THE PERL DEBUGGER**\n- **LOGGING**\n- **OBJECT-ORIENTED TECHNIQUES** (5 subsections)\n- **COMMON TRAPS**\n- **MASON AND SOURCE FILTERS**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "HTML::Mason::Devel",
        "section": "",
        "mode": "perldoc",
        "summary": "HTML::Mason::Devel - Mason Developer's Manual",
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 20,
                "subsections": []
            },
            {
                "name": "HOW TO USE THIS MANUAL",
                "lines": 66,
                "subsections": []
            },
            {
                "name": "IN-LINE PERL SECTIONS",
                "lines": 35,
                "subsections": [
                    {
                        "name": "Examples and Recommended Usage",
                        "lines": 63
                    }
                ]
            },
            {
                "name": "MASON OBJECTS",
                "lines": 3,
                "subsections": [
                    {
                        "name": "Request Objects",
                        "lines": 20
                    },
                    {
                        "name": "Component Objects",
                        "lines": 8
                    },
                    {
                        "name": "System Objects",
                        "lines": 6
                    }
                ]
            },
            {
                "name": "CALLING COMPONENTS",
                "lines": 3,
                "subsections": [
                    {
                        "name": "Components that output HTML",
                        "lines": 50
                    },
                    {
                        "name": "Component Calls with Content",
                        "lines": 59
                    },
                    {
                        "name": "Advanced Components Calls with Content",
                        "lines": 76
                    },
                    {
                        "name": "Components that Return Values",
                        "lines": 47
                    },
                    {
                        "name": "Subrequests",
                        "lines": 48
                    }
                ]
            },
            {
                "name": "TOP-LEVEL COMPONENTS",
                "lines": 148,
                "subsections": []
            },
            {
                "name": "PASSING PARAMETERS",
                "lines": 3,
                "subsections": [
                    {
                        "name": "In Component Calls",
                        "lines": 7
                    },
                    {
                        "name": "In HTTP requests",
                        "lines": 7
                    },
                    {
                        "name": "Accessing Parameters",
                        "lines": 44
                    },
                    {
                        "name": "Parameter Passing Examples",
                        "lines": 60
                    }
                ]
            },
            {
                "name": "INITIALIZATION AND CLEANUP",
                "lines": 123,
                "subsections": []
            },
            {
                "name": "EMBEDDED COMPONENTS",
                "lines": 62,
                "subsections": []
            },
            {
                "name": "FLAGS AND ATTRIBUTES",
                "lines": 34,
                "subsections": []
            },
            {
                "name": "FILTERING",
                "lines": 47,
                "subsections": []
            },
            {
                "name": "COMMENT MARKERS",
                "lines": 47,
                "subsections": []
            },
            {
                "name": "OTHER SYNTAX",
                "lines": 14,
                "subsections": [
                    {
                        "name": "Escaping expressions",
                        "lines": 87
                    },
                    {
                        "name": "Backslash at end of line",
                        "lines": 33
                    }
                ]
            },
            {
                "name": "DATA CACHING",
                "lines": 14,
                "subsections": [
                    {
                        "name": "Basic Usage",
                        "lines": 27
                    },
                    {
                        "name": "Expiration",
                        "lines": 22
                    },
                    {
                        "name": "Avoiding Concurrent Recomputation",
                        "lines": 36
                    },
                    {
                        "name": "Caching All Output",
                        "lines": 16
                    },
                    {
                        "name": "Cache Object",
                        "lines": 7
                    },
                    {
                        "name": "Choosing a Cache Subclass - with Cache::Cache",
                        "lines": 19
                    },
                    {
                        "name": "Choosing a Cache Subclass - with CHI",
                        "lines": 18
                    },
                    {
                        "name": "Accessing a Cache Externally",
                        "lines": 33
                    },
                    {
                        "name": "Mason 1.0x Cache API",
                        "lines": 8
                    }
                ]
            },
            {
                "name": "WEB-SPECIFIC FEATURES",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Sending HTTP Headers",
                        "lines": 36
                    },
                    {
                        "name": "Returning HTTP Status",
                        "lines": 37
                    },
                    {
                        "name": "External Redirects",
                        "lines": 17
                    },
                    {
                        "name": "Internal Redirects",
                        "lines": 16
                    }
                ]
            },
            {
                "name": "USING THE PERL DEBUGGER",
                "lines": 30,
                "subsections": []
            },
            {
                "name": "LOGGING",
                "lines": 9,
                "subsections": []
            },
            {
                "name": "OBJECT-ORIENTED TECHNIQUES",
                "lines": 20,
                "subsections": [
                    {
                        "name": "Determining inheritance",
                        "lines": 17
                    },
                    {
                        "name": "Content wrapping",
                        "lines": 5
                    },
                    {
                        "name": "Accessing methods and attributes",
                        "lines": 69
                    },
                    {
                        "name": "Sharing data",
                        "lines": 37
                    },
                    {
                        "name": "Example",
                        "lines": 64
                    }
                ]
            },
            {
                "name": "COMMON TRAPS",
                "lines": 19,
                "subsections": []
            },
            {
                "name": "MASON AND SOURCE FILTERS",
                "lines": 4,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "HTML::Mason::Devel - Mason Developer's Manual\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This manual is written for content developers who know HTML and at least a little Perl. The goal\nis to write, run, and debug Mason components.\n\nIf you are the webmaster (or otherwise responsible for the Mason installation), you should also\nread the administrator's manual. There you will find information about site configuration,\nperformance tuning, component caching, and so on.\n\nIf you are a developer just interested in knowing more about Mason's capabilities and\nimplementation, then the administrator's manual is for you too.\n\nWe strongly suggest that you have a working Mason to play with as you work through these\nexamples. Other component examples can be found in the \"samples/\" directory.\n\nWhile Mason can be used for tasks besides implementing a dynamic web site, that is what *most*\npeople want to do with Mason, and is thus the focus of this manual.\n\nIf you are planning to use Mason outside of the web, this manual will still be useful, of\ncourse. Also make sure to read the running outside of modperl section of the administrator's\nmanual.\n",
                "subsections": []
            },
            "HOW TO USE THIS MANUAL": {
                "content": "If you are just learning Mason and want to get started quickly, we recommend the following\nsections:\n\no What Are Components?\n\no In-Line Perl Sections\n\no Calling Components\n\no Top-Level Components\n\no Passing Parameters\n\no Initialization and Cleanup (mainly \"<%init>\")\n\no Web-Specific Features\n\no Common Traps\n\nWHAT ARE COMPONENTS?\nThe component - a mix of Perl and HTML - is Mason's basic building block and computational unit.\nUnder Mason, web pages are formed by combining the output from multiple components. An article\npage for a news publication, for example, might call separate components for the company\nmasthead, ad banner, left table of contents, and article body. Consider this layout sketch:\n\n+---------+------------------+\n|Masthead | Banner Ad        |\n+---------+------------------+\n|         |                  |\n|+-------+|Text of Article ..|\n||       ||                  |\n||Related||Text of Article ..|\n||Stories||                  |\n||       ||Text of Article ..|\n|+-------+|                  |\n|         +------------------+\n|         | Footer           |\n+---------+------------------+\n\nThe top level component decides the overall page layout, perhaps with HTML tables. Individual\ncells are then filled by the output of subordinate components, one for the Masthead, one for the\nFooter, etc. In practice pages are built up from as few as one, to as many as twenty or more\ncomponents.\n\nThis component approach reaps many benefits in a web environment. The first benefit is\n*consistency*: by embedding standard design elements in components, you ensure a consistent look\nand make it possible to update the entire site with just a few edits. The second benefit is\n*concurrency*: in a multi-person environment, one person can edit the masthead while another\nedits the table of contents. A last benefit is *reuseability*: a component produced for one site\nmight be useful on another. You can develop a library of generally useful components to employ\non your sites and to share with others.\n\nMost components emit chunks of HTML. \"Top level\" components, invoked from a URL, represent an\nentire web page. Other, subordinate components emit smaller bits of HTML destined for inclusion\nin top level components.\n\nComponents receive form and query data from HTTP requests. When called from another component,\nthey can accept arbitrary parameter lists just like a subroutine, and optionally return values.\nThis enables a type of component that does not print any HTML, but simply serves as a function,\ncomputing and returning a result.\n\nMason actually compiles components down to Perl subroutines, so you can debug and profile\ncomponent-based web pages with standard Perl tools that understand the subroutine concept, e.g.\nyou can use the Perl debugger to step through components, and Devel::DProf to profile their\nperformance.\n",
                "subsections": []
            },
            "IN-LINE PERL SECTIONS": {
                "content": "Here is a simple component example:\n\n<%perl>\nmy $noun = 'World';\nmy @time = localtime;\n</%perl>\nHello <% $noun %>,\n% if ( $time[2] < 12 ) {\ngood morning.\n% } else {\ngood afternoon.\n% }\n\nAfter 12 pm, the output of this component is:\n\nHello World, good afternoon.\n\nThis short example demonstrates the three primary \"in-line\" Perl sections. In-line sections are\ngenerally embedded within HTML and execute in the order they appear. Other sections (\"<%init>\",\n\"<%args>\", etc.) are tied to component events like initialization, cleanup, and argument\ndefinition.\n\nThe parsing rules for these Perl sections are as follows:\n\n1.  Blocks of the form <% xxx %> are replaced with the result of evaluating xxx as a single Perl\nexpression. These are often used for variable replacement. such as 'Hello, <% $name %>!'.\n\n2.  Lines beginning with a '%' character are treated as Perl.\n\n3.  Multiline blocks of Perl code can be inserted with the \"<%perl>\" .. \"</%perl>\" tag. The\nenclosed text is executed as Perl and the return value, if any, is discarded.\n\nThe \"<%perl>\" tag, like all block tags in Mason, is case-insensitive. It may appear anywhere\nin the text, and may span any number of lines.\n",
                "subsections": [
                    {
                        "name": "Examples and Recommended Usage",
                        "content": "% lines\n\nMost useful for conditional and loop structures - if, while, foreach, , etc. - as well as\nside-effect commands like assignments. To improve readability, always put a space after the '%'.\nExamples:\n\no Conditional code\n\n% my $ua = $r->headerin('User-Agent');\n% if ($ua =~ /msie/i) {\nWelcome, Internet Explorer users\n...\n% } elsif ($ua =~ /mozilla/i) {\nWelcome, Netscape users\n...\n% }\n\no HTML list formed from array\n\n<ul>\n% foreach $item (@list) {\n<li><% $item %></li>\n% }\n</ul>\n\no HTML list formed from hash\n\n<ul>\n% while (my ($key,$value) = each(%ENV)) {\n<li>\n<b><% $key %></b>: <% $value %>\n</li>\n% }\n</ul>\n\no HTML table formed from list of hashes\n\n<table>\n% foreach my $h (@loh) {\n<tr>\n<td><% $h->{foo} %></td>\n<td bgcolor=#ee0000><% $h->{bar} %></td>\n<td><% $h->{baz} %></td>\n</tr>\n% }\n</table>\n\n<% xxx %>\n\nMost useful for printing out variables, as well as more complex expressions. To improve\nreadability, always separate the tag and expression with spaces. Examples:\n\nDear <% $name %>: We will come to your house at <% $address %> in the\nfair city of <% $city %> to deliver your $<% $amount %> dollar prize!\n\nThe answer is <% ($y+8) % 2 %>.\n\nYou are <% $age < 18 ? 'not' : '' %> permitted to enter this site.\n\n<%perl> xxx </%perl>\n\nUseful for Perl blocks of more than a few lines.\n"
                    }
                ]
            },
            "MASON OBJECTS": {
                "content": "This section describes the various objects in the Mason universe. If you're just starting out,\nall you need to worry about initially are the request objects.\n",
                "subsections": [
                    {
                        "name": "Request Objects",
                        "content": "Two global per-request objects are available to all components: $r and $m.\n\n$r, the modperl request object, provides a Perl API to the current Apache request. It is fully\ndescribed in Apache.pod. Here is a sampling of methods useful to component developers:\n\n$r->uri             # the HTTP request URI\n$r->headerin(..)   # get the named HTTP header line\n$r->contenttype    # set or retrieve content-type\n$r->headerout(..)  # set or retrieve an outgoing header\n\n$r->content         # don't use this one! (see Tips and Traps)\n\n$m, the Mason request object, provides an analogous API for Mason. Almost all Mason features not\nactivated by syntactic tags are accessed via $m methods. You'll be introduced to these methods\nthroughout this document as they are needed. For a description of all methods see\nHTML::Mason::Request.\n\nBecause these are always set inside components, you should not ever define other variables with\nthe same name, or else your code may fail in strange and mysterious ways.\n"
                    },
                    {
                        "name": "Component Objects",
                        "content": "Mason provides an object API for components, allowing you to query a component's various\nassociated files, arguments, etc. For a description of all methods see HTML::Mason::Component.\nTypically you get a handle on a component object from request methods like \"$m->currentcomp\"\nand \"$m->fetchcomp\".\n\nNote that for many basic applications all you'll want to do with components is call them, for\nwhich no object method is needed. See next section.\n"
                    },
                    {
                        "name": "System Objects",
                        "content": "Many system objects share the work of serving requests in Mason: HTML::Mason::Lexer,\nHTML::Mason::Compiler, HTML::Mason::Interp, HTML::Mason::Resolver, and\nHTML::Mason::ApacheHandler are examples. The administrator creates these objects and provides\nparameters that shape Mason's behavior. As a pure component developer you shouldn't need to\nworry about or access these objects, but occasionally we'll mention a relevant parameter.\n"
                    }
                ]
            },
            "CALLING COMPONENTS": {
                "content": "Mason pages often are built not from a single component, but from multiple components that call\neach other in a hierarchical fashion.\n",
                "subsections": [
                    {
                        "name": "Components that output HTML",
                        "content": "To call one component from another, use the <& &> tag:\n\n<& comppath, [name=>value, ...] &>\n\ncomppath:\nThe component path. With a leading '/', the path is relative to the component root\n(comproot). Otherwise, it is relative to the location of the calling component.\n\nname => value pairs:\nParameters are passed as one or more \"name => value\" pairs, e.g. \"player => 'M. Jordan'\".\n\ncomppath may be a literal string (quotes optional) or a Perl expression that evaluates to a\nstring. To eliminate the need for quotes in most cases, Mason employs some magic parsing: If the\nfirst character is one of \"[\\w/.]\", comppath is assumed to be a literal string running up to\nthe first comma or &>. Otherwise, comppath is evaluated as an expression.\n\nHere are some examples:\n\n# relative component paths\n<& topimage &>\n<& tools/searchbox &>\n\n# absolute component path\n<& /shared/masthead, color=>'salmon' &>\n\n# this component path MUST have quotes because it contains a comma\n<& \"sugar,eggs\", mix=>1 &>\n\n# variable component path\n<& $comp &>\n\n# variable component and arguments\n<& $comp, %args &>\n\n# you can use arbitrary expression for component path, but it cannot\n# begin with a letter or number; delimit with () to remedy this\n<& (int(rand(2)) ? 'thiscomp' : 'thatcomp'), id=>123 &>\n\nSeveral request methods also exist for calling components. \"$m->comp\" performs the equivalent\naction to <& &>:\n\n$m->comp('/shared/masthead', color=>'salmon');\n\n\"$m->scomp\" is like the sprintf version of \"$m->comp\": it returns the component output, allowing\nthe caller to examine and modify it before printing:\n\nmy $masthead = $m->scomp('/shared/masthead', color=>'salmon');\n$masthead =~ ...;\n$m->print($masthead);\n"
                    },
                    {
                        "name": "Component Calls with Content",
                        "content": "Components can be used to filter part of the page's content using an extended component syntax.\n\n<&| /path/to/comp &> this is the content </&>\n<&| comp, arg1 => 'hi' &> filters can take arguments </&>\n<&| comp &> content can include <% \"tags\" %> of all kinds </&>\n<&| comp1 &> nesting is also <&| comp2 &> OK </&> </&>\n<&| SELF:method1 &> subcomponents can be filters </&>\n\nThe filtering component can be called in all the same ways a normal component is called, with\narguments and so forth. The only difference between a filtering component and a normal component\nis that a filtering component is expected to fetch the content by calling $m->content and do\nsomething with it.\n\nThe ending tag may optionally contain the name of the component, and Mason will verify that it\nmatches the name in the starting tag. This may be helpful when the tags are far apart or nested.\nTo avoid ambiguous situations, this is only allowed when the component name is an unquoted\nliteral (starting with \"[\\w/.]\"). For anything more complicated, such as \"<|& $var &>\" or \"<&|\n'name' &>\", the simple \"</&>\" form must be used.\n\n<&| \"outer\" &>\n<&| /inner/comp, arg=>'this' &>\n<&| .mycomp &>\nYada yada yada\n</& .mycomp >\n</& /inner/comp >\n</&>\n\nHere is an example of a component used for localization. Its content is a series of strings in\ndifferent languages, and it selects the correct one based on a global $lang variable, which\ncould be setup in a site-level autohandler.\n\n<&| /i18n/itext &>\n<en>Hello, <% $name %> This is a string in English</en>\n<de>Schoene Gruesse, <% $name %>, diese Worte sind auf Deutsch</de>\n<pig>ellohay <% substr($name,2).substr($name,1,1).'ay' %>,\nisthay isay igpay atinlay</pig>\n</&>\n\nHere is the /i18n/itext component:\n\n<% $text %>\n\n<%init>\n# this assumes $lang is a global variable which has been set up earlier.\nlocal $ = $m->content;\nmy ($text) = m{<$lang>(.*?)</$lang>};\n</%init>\n\nYou can explicitly check whether a component has passed content by checking the boolean\n\"$m->hascontent\". This allows you to write a component that will do different things depending\non whether it was passed content. However, before overloading a component in this way, consider\nwhether splitting the behavior into two distinct components would work as well.\n\nIf a normal component which does not call \"$m->content\" is called with content, the content will\nnot be output.\n\nIf you wrap a filtering component call around the entire component, the result will be\nfunctionally similar to a \"<%filter>\" section. See also Filtering.\n"
                    },
                    {
                        "name": "Advanced Components Calls with Content",
                        "content": "Internally \"$m->content\" is implemented with a closure containing the part of the component\nwhich is the content. In English, that means that any mason tags and perl code in the content\nare evaluated when \"$m->content\" is called, and \"$m->content\" returns the text which would have\nbeen output by mason. Because the contents are evaluated at the time that \"$m->content\" is\ncalled, one can write components which act as control structures or which output their contents\nmultiple times with different values for the variables (can you say taglibs?).\n\nThe tricky part of using filter components as control structures is setting up variables which\ncan be accessed from both the filter component and the content, which is in the component which\ncalls the filter component. The content has access to all variables in the surrounding\ncomponent, but the filtering component does not. There are two ways to do this: use global\nvariables, or pass a reference to a lexical variable to the filter component.\n\nHere is a simple example using the second method:\n\n% my $var;\n<ol>\n<&| listitems , list => \\@items, var => \\$var &>\n<li> <% $var %></li>\n</&>\n</ol>\n\nlistitems component:\n\n<%args>\n@list\n$var\n</%args>\n% foreach (@list) {\n% $$var = $;  # $var is a reference\n<% $m->content %>\n% }\n\nUsing global variables can be somewhat simpler. Below is the same example, with $var defined as\na global variable. The site administrator must make sure that $var is included in Mason's\nallowglobals parameter. Local-izing $var within the filter component will allow the listitems\ncomponent to be nested.\n\n<ol>\n<&| listitems, list => \\@items &>\n<li> <% $var %></li>\n</&>\n</ol>\n\nlistitems component:\n\n<%args>\n@list\n</%args>\n% foreach (@list) {\n% local $var = $;\n<% $m->content %>\n% }\n\nBesides remembering to include $var in allowglobals, the developers should take care not to use\nthat variable is other places where it might conflict with usage by the filter component.\nLocal-izing $var will also provide some protection against using it in other places.\n\nAn even simpler method is to use the $ variable. It is already global, and is automatically\nlocal-ized by the foreach statement:\n\n<ol>\n<&| listitems, list => \\@items &>\n<li> <% $ %> </li>\n</&>\n</ol>\n\nlistitems component:\n\n<%args>\n@list\n</%args>\n% foreach (@list) {\n<% $m->content %>\n% }\n"
                    },
                    {
                        "name": "Components that Return Values",
                        "content": "So far you have seen components used solely to output HTML. However, components may also be used\nto return values.\n\nWhile we will demonstrate how this is done, we strongly encourage you to put code like this in\nmodules instead. There are several reasons why this is a good idea:\n\n*   You can re-use this code outside of Mason.\n\n*   It is easy to preload module code when running under modperl, which can lower memory usage.\n\n*   Using Mason components as subroutines is slower than just using modules to do the same\nthing.\n\n*   It's easier to regression test module code.\n\nWith that being said, there are times when you may want to write a component which returns a\nvalue.\n\nAs an example, you might have a component \"isnetscape\" that analyzes the user agent to\ndetermine whether it is a Netscape browser:\n\n<%init>\nmy $ua = $r->headerin('User-Agent');\nreturn ($ua =~ /Mozilla/i && $ua !~ /MSIE/i) ? 1 : 0;\n</%init>\n\nBecause components are implemented underneath with Perl subroutines, they can return values and\neven understand scalar/list context. e.g. The result of wantarray() inside a component will\nreflect whether the component was called in scalar or list context.\n\nThe <& &> notation only calls a component for its side-effect, and discards its return value, if\nany. To get at the return value of a component, use the \"$m->comp\" command:\n\n% if ($m->comp('isnetscape')) {\nWelcome, Netscape user!\n% }\n\nMason adds a \"return undef\" to the bottom of each component to provide an empty default return\nvalue. To return your own value from a component, you *must* use an explicit \"return\" statement.\nYou cannot rely on the usual Perl trick of letting return values \"fall through\".\n\nWhile it is possible for a component to generate output and return values, there is very little\nreason for a component to do both. For example, it would not be very friendly for \"isnetscape\"\nto output \"hi Mom\" while it was computing its value, thereby surprising the \"if\" statement!\nConversely, any value returned by an output generating component would typically be discarded by\nthe <& &> tag that invoked it.\n"
                    },
                    {
                        "name": "Subrequests",
                        "content": "You may sometimes want to have a component call go through all the steps that the initial\ncomponent call goes through, such as checking for autohandlers and dhandlers. To do this, you\nneed to execute a subrequest.\n\nA subrequest is simply a Mason Request object and has all of the methods normally associated\nwith one.\n\nTo create a subrequest you simply use the \"$m->makesubrequest\" method. This method can take any\nparameters belonging to HTML::Mason::Request, such as autoflush or outmethod. Once you have a\nnew request object you simply call its \"exec\" method to execute it, which takes exactly the same\nparameters as the \"comp\" method.\n\nSince subrequests inherit their parent request's parameters, output from a component called via\na subrequest goes to the same destination as output from components called during the parent\nrequest. Of course, you can change this.\n\nHere are some examples:\n\n<%perl>\nmy $req = $m->makesubrequest( comp => '/some/comp', args => [ id => 172 ] );\n$req->exec;\n</%perl>\n\nIf you want to capture the subrequest's output in a scalar, you can simply pass an outmethod\nparameter to \"$m->makesubrequest\":\n\n<%perl>\nmy $buffer;\nmy $req =\n$m->makesubrequest\n( comp => '/some/comp', args => [ id => 172 ], outmethod => \\$buffer );\n$req->exec;\n</%perl>\n\nNow $buffer contains all the output from that call to /some/comp.\n\nFor convenience, Mason also provides an \"$m->subexec\" method. This method takes the same\narguments as \"$m->comp\" and internally calls \"$m->makesubrequest\" and then \"exec\" on the\ncreated request, all in one fell swoop. This is useful in cases where you have no need to\noverride any of the parent request object's attributes.\n\nBy default, output from a subrequest appears inline in the calling component, at the point where\nit is executed. If you wish to do something else, you will need to explicitly override the\nsubrequest's outmethod parameter.\n\nMason Request objects are only designed to handle a single call to \"exec\". If you wish to make\nmultiple subrequests, you must create a new subrequest object for each one.\n"
                    }
                ]
            },
            "TOP-LEVEL COMPONENTS": {
                "content": "The first component invoked for a page (the \"top-level component\") resides within the\nDocumentRoot and is chosen based on the URL. For example:\n\nhttp://www.foo.com/mktg/prods.html?id=372\n\nMason converts this URL to a filename, e.g. /usr/local/www/htdocs/mktg/prods.html. Mason loads\nand executes that file as a component. In effect, Mason calls\n\n$m->comp('/mktg/prods.html', id=>372)\n\nThis component might in turn call other components and execute some Perl code, or it might\ncontain nothing more than static HTML.\n\ndhandlers\nWhat happens when a user requests a component that doesn't exist? In this case Mason scans\nbackward through the URI, checking each directory for a component named *dhandler* (\"default\nhandler\"). If found, the dhandler is invoked and is expected to use \"$m->dhandlerarg\" as the\nparameter to some access function, perhaps a database lookup or location in another filesystem.\nIn a sense, dhandlers are similar in spirit to Perl's AUTOLOAD feature; they are the \"component\nof last resort\" when a URL points to a non-existent component.\n\nConsider the following URL, in which newsfeeds/ exists but not the subdirectory LocalNews nor\nthe component Story1:\n\nhttp://myserver/newsfeeds/LocalNews/Story1\n\nIn this case Mason constructs the following search path:\n\n/newsfeeds/LocalNews/Story1         => no such thing\n/newsfeeds/LocalNews/dhandler       => no such thing\n/newsfeeds/dhandler                 => found! (search ends)\n/dhandler\n\nThe found dhandler would read \"LocalNews/Story1\" from \"$m->dhandlerarg\" and use it as a\nretrieval key into a database of stories.\n\nHere's how a simple /newsfeeds/dhandler might look:\n\n<& header &>\n<b><% $headline %></b><p>\n<% $body %>\n<& footer &>\n\n<%init>\nmy $arg = $m->dhandlerarg;                # get rest of path\nmy ($section, $story) = split(\"/\", $arg);  # split out pieces\nmy $sth = $DBH->prepare\n(qq{SELECT headline,body FROM news\nWHERE section = ? AND story = ?);\n$sth->execute($section, $story);\nmy ($headline, $body) = $sth->fetchrowarray;\nreturn 404 if !$headline;                  # return \"not found\" if no such story\n</%init>\n\nBy default dhandlers do not get a chance to handle requests to a directory itself (e.g.\n/newsfeeds). These are automatically deferred to Apache, which generates an index page or a\nFORBIDDEN error. Often this is desirable, but if necessary the administrator can let in\ndirectory requests as well; see the allowing directory requests section of the administrator's\nmanual.\n\nA component or dhandler that does not want to handle a particular request may defer control to\nthe next dhandler by calling \"$m->decline\".\n\nWhen using dhandlers under modperl, you may find that sometimes Apache will not set a content\ntype for a response. This usually happens when a dhandler handles a request for a non-existent\nfile or directory. You can add a \"<Location>\" or \"<LocationMatch>\" block containing a \"SetType\"\ndirective to your Apache config file, or you can just set the content type dynamically by\ncalling \"$r->contenttype\".\n\nThe administrator can customize the file name used for dhandlers with the dhandlername\nparameter.\n\nautohandlers\nAutohandlers allow you to grab control and perform some action just before Mason calls the\ntop-level component. This might mean adding a standard header and footer, applying an output\nfilter, or setting up global variables.\n\nAutohandlers are directory based. When Mason determines the top-level component, it checks that\ndirectory and all parent directories for a component called autohandler. If found, the\nautohandler is called first. After performing its actions, the autohandler typically calls\n\"$m->callnext\" to transfer control to the original intended component.\n\n\"$m->callnext\" works just like \"$m->comp\" except that the component path and arguments are\nimplicit. You can pass additional arguments to \"$m->callnext\"; these are merged with the\noriginal arguments, taking precedence in case of conflict. This allows you, for example, to\noverride arguments passed in the URL.\n\nHere is an autohandler that adds a common header and footer to each page underneath its\ndirectory:\n\n<html>\n<head><title>McHuffy Incorporated</title></head>\n<body style=\"background-color: pink\">\n\n% $m->callnext;\n\n<hr />\nCopyright 1999 McHuffy Inc.\n</body>\n</html>\n\nSame idea, using components for the header/footer:\n\n<& /shared/header &>\n% $m->callnext;\n<& /shared/footer &>\n\nThe next autohandler applies a filter to its pages, adding an absolute hostname to relative\nimage URLs:\n\n% $m->callnext;\n\n<%filter>\ns{(<img[^>]+src=\\\")/} {$1http://images.mysite.com/}ig;\n</%filter>\n\nMost of the time autohandler can simply call \"$m->callnext\" without needing to know what the\nnext component is. However, should you need it, the component object is available from\n\"$m->fetchnext\". This is useful for calling the component manually, e.g. if you want to\nsuppress some original arguments or if you want to use \"$m->scomp\" to store and process the\noutput.\n\nIf more than one autohandler applies to a page, each autohandler gets a chance to run. The\ntop-most autohandler runs first; each \"$m->callnext\" transfers control to the next autohandler\nand finally to the originally called component. This allows you, for example, to combine general\nsite-wide templates and more specific section-based templates.\n\nAutohandlers can be made even more powerful in conjunction with Mason's object-oriented style\nfeatures: methods, attributes, and inheritance. In the interest of space these are discussed in\na separate section, Object-Oriented Techniques.\n\nThe administrator can customize the file name used for autohandlers with the autohandlername\nparameter.\n\ndhandlers vs. autohandlers\ndhandlers and autohandlers both provide a way to exert control over a large set of URLs.\nHowever, each specializes in a very different application. The key difference is that dhandlers\nare invoked only when no appropriate component exists, while autohandlers are invoked only in\nconjunction with a matching component.\n\nAs a rule of thumb: use an autohandler when you have a set of components to handle your pages\nand you want to augment them with a template/filter. Use a dhandler when you want to create a\nset of \"virtual URLs\" that don't correspond to any actual components, or to provide default\nbehavior for a directory.\n\ndhandlers and autohandlers can even be used in the same directory. For example, you might have a\nmix of real URLs and virtual URLs to which you would like to apply a common template/filter.\n",
                "subsections": []
            },
            "PASSING PARAMETERS": {
                "content": "This section describes Mason's facilities for passing parameters to components (either from HTTP\nrequests or component calls) and for accessing parameter values inside components.\n",
                "subsections": [
                    {
                        "name": "In Component Calls",
                        "content": "Any Perl data type can be passed in a component call:\n\n<& /sales/header, s => 'dog', l => [2, 3, 4], h => {a => 7, b => 8} &>\n\nThis command passes a scalar ($s), a list (@l), and a hash (%h). The list and hash must be\npassed as references, but they will be automatically dereferenced in the called component.\n"
                    },
                    {
                        "name": "In HTTP requests",
                        "content": "Consider a CGI-style URL with a query string:\n\nhttp://www.foo.com/mktg/prods.html?str=dog&lst=2&lst=3&lst=4\n\nor an HTTP request with some POST content. Mason automatically parses the GET/POST values and\nmakes them available to the component as parameters.\n"
                    },
                    {
                        "name": "Accessing Parameters",
                        "content": "Component parameters, whether they come from GET/POST or another component, can be accessed in\ntwo ways.\n\n1. Declared named arguments: Components can define an \"<%args>\" section listing argument names,\ntypes, and default values. For example:\n\n<%args>\n$a\n@b       # a comment\n%c\n\n# another comment\n$d => 5\n$e => $d*2\n@f => ('foo', 'baz')\n%g => (joe => 1, bob => 2)\n</%args>\n\nHere, *$a*, *@b*, and *%c* are required arguments; the component generates an error if the\ncaller leaves them unspecified. *$d*, *$e*, *@f* and *%g* are optional arguments; they are\nassigned the specified default values if unspecified. All the arguments are available as\nlexically scoped (\"my\") variables in the rest of the component.\n\nArguments are separated by one or more newlines. Comments may be used at the end of a line or on\ntheir own line.\n\nDefault expressions are evaluated in top-to-bottom order, and one expression may reference an\nearlier one (as $e references $d above).\n\nOnly valid Perl variable names may be used in \"<%args>\" sections. Parameters with non-valid\nvariable names cannot be pre-declared and must be fetched manually out of the %ARGS hash (see\nbelow). One common example of undeclarable parameters are the \"button.x/button.y\" parameters\nsent for a form submit.\n\n2. %ARGS hash: This variable, always available, contains all of the parameters passed to the\ncomponent (whether or not they were declared). It is especially handy for dealing with large\nnumbers of parameters, dynamically named parameters, or parameters with non-valid variable\nnames. %ARGS can be used with or without an \"<%args>\" section, and its contents are unrelated to\nwhat you have declared in \"<%args>\".\n\nHere's how to pass all of a component's parameters to another component:\n\n<& template, %ARGS &>\n"
                    },
                    {
                        "name": "Parameter Passing Examples",
                        "content": "The following examples illustrate the different ways to pass and receive parameters.\n\n1. Passing a scalar *id* with value 5.\n\nIn a URL: /my/URL?id=5\nIn a component call: <& /my/comp, id => 5 &>\nIn the called component, if there is a declared argument named...\n$id, then $id will equal 5\n@id, then @id will equal (5)\n%id, then an error occurs\nIn addition, $ARGS{id} will equal 5.\n\n2. Passing a list *colors* with values red, blue, and green.\n\nIn a URL: /my/URL?colors=red&colors=blue&colors=green\nIn an component call: <& /my/comp, colors => ['red', 'blue', 'green'] &>\nIn the called component, if there is a declared argument named...\n$colors, then $colors will equal ['red', 'blue', 'green']\n@colors, then @colors will equal ('red', 'blue', 'green')\n%colors, then an error occurs\nIn addition, $ARGS{colors} will equal ['red', 'blue', 'green'].\n\n3. Passing a hash *grades* with pairs Alice => 92 and Bob => 87.\n\nIn a URL: /my/URL?grades=Alice&grades=92&grades=Bob&grades=87\nIn an component call: <& /my/comp, grades => {Alice => 92, Bob => 87} &>\nIn the called component, if there is a declared argument named...\n@grades, then @grades will equal ('Alice', 92, 'Bob', 87)\n%grades, then %grades will equal (Alice => 92, Bob => 87)\nIn addition, $grade and $ARGS{grades} will equal\n['Alice',92,'Bob',87] in the URL case, or {Alice => 92, Bob => 87}\nin the component call case.  (The discrepancy exists because, in a\nquery string, there is no detectable difference between a list or\nhash.)\n\nUsing @ instead\nIf you don't like named parameters, you can pass a traditional list of ordered parameters:\n\n<& /mktg/prods.html', 'dog', [2, 3, 4], {a => 7, b => 8} &>\n\nand access them as usual through Perl's @ array:\n\nmy ($scalar, $listref, $hashref) = @;\n\nIn this case no \"<%args>\" section is necessary.\n\nWe generally recommend named parameters for the benefits of readability, syntax checking, and\ndefault value automation. However using @ may be convenient for very small components,\nespecially subcomponents created with \"<%def>\".\n\nBefore Mason 1.21, @ contained *copies* of the caller's arguments. In Mason 1.21 and beyond,\nthis unnecessary copying was eliminated and @ now contains *aliases* to the caller's arguments,\njust as with regular Perl subroutines. For example, if a component updates $[0], the\ncorresponding argument is updated (or an error occurs if it is not updateable).\n\nMost users won't notice this change because \"<%args>\" variables and the %ARGS hash always\ncontain copies of arguments.\n\nSee perlsub for more information on @ aliasing.\n"
                    }
                ]
            },
            "INITIALIZATION AND CLEANUP": {
                "content": "The following sections contain blocks of Perl to execute at specific times.\n\n<%init>\nThis section contains initialization code that executes as soon as the component is called. For\nexample: checking that a user is logged in; selecting rows from a database into a list; parsing\nthe contents of a file into a data structure.\n\nTechnically an \"<%init>\" block is equivalent to a \"<%perl>\" block at the beginning of the\ncomponent. However, there is an aesthetic advantage of placing this block at the end of the\ncomponent rather than the beginning.\n\nWe've found that the most readable components (especially for non-programmers) contain HTML in\none continuous block at the top, with simple substitutions for dynamic elements but no\ndistracting blocks of Perl code. At the bottom an \"<%init>\" block sets up the substitution\nvariables. This organization allows non-programmers to work with the HTML without getting\ndistracted or discouraged by Perl code. For example:\n\n<html>\n<head><title><% $headline %></title></head>\n<body>\n<h2><% $headline %></h2>\n<p>By <% $author %>, <% $date %></p>\n\n<% $body %>\n\n</body>\n</html>\n\n<%init>\n# Fetch article from database\nmy $dbh = DBI::connect ...;\nmy $sth = $dbh->prepare(\"select * from articles where id = ?\");\n$sth->execute($articleid);\nmy ($headline, $date, $author, $body) = $sth->fetchrowarray;\n# Massage the fields\n$headline = uc($headline);\nmy ($year, $month, $day) = split('-', $date);\n$date = \"$month/$day\";\n</%init>\n\n<%args>\n$articleid\n</%args>\n\n<%cleanup>\nThis section contains cleanup code that executes just before the component exits. For example:\nclosing a database connection or closing a file handle.\n\nA \"<%cleanup>\" block is equivalent to a \"<%perl>\" block at the end of the component. This means\nit will NOT execute if the component explicitly returns, or if an abort or error occurs in that\ncomponent or one of its children. Because of this limitation, and because Perl is usually so\ngood about cleaning up at the end of a lexical scope (e.g. component), \"<%cleanup>\" sections are\nrarely needed.\n\nIf you need code that is guaranteed to run when the component or request exits, consider using a\nmodperl cleanup handler, or creating a custom class with a DESTROY method.\n\n<%once>\nThis code executes once when the component is loaded. Variables declared in this section can be\nseen in all of a component's code and persist for the lifetime of the component.\n\nThis section is useful for declaring persistent component-scoped lexical variables (especially\nobjects that are expensive to create), declaring subroutines (both named and anonymous), and\ninitializing state.\n\nThis code does not run inside a request context. You cannot call components or access $m or $r\nfrom this section. Also, do not attempt to \"return()\" from a \"<%once>\" section; the current\ncompiler cannot properly handle it.\n\nNormally this code will execute individually from every HTTP child that uses the component.\nHowever, if the component is preloaded, this code will only execute once in the parent. Unless\nyou have total control over what components will be preloaded, it is safest to avoid\ninitializing variables that can't survive a fork(), e.g. DBI handles. Use code like this to\ninitialize such variables in the \"<%init>\" section:\n\n<%once>\nmy $dbh;      # declare but don't assign\n...\n</%once>\n\n<%init>\n$dbh ||= DBI::connect ...\n...\n</%init>\n\nIn addition, using $m or $r in this section will not work in a preloaded component, because\nneither of those variable exist when a component is preloaded.\n\n<%shared>\nAs with \"<%once>\", lexical (\"my\") variables declared in this section can be seen in all the rest\nof a component's code: the main body, subcomponents, and methods. However, unlike \"<%once>\", the\ncode runs once per request (whenever the component is used) and its variables last only until\nthe end of the request.\n\nA \"<%shared>\" section is useful for initializing variables needed in, say, the main body and one\nmore subcomponents or methods. See Object-Oriented Techniques for an example of usage.\n\nIt's important to realize that you do not have access to the %ARGS hash or variables created via\nan \"<%args>\" block inside a shared section. However, you can access arguments via\n$m->requestargs.\n\nAdditionally, you cannot call a components' own methods or subcomponents from inside a\n\"<%shared>\", though you can call other components.\n\nAvoid using \"<%shared>\" for side-effect code that needs to run at a predictable time during page\ngeneration. You may assume only that \"<%shared>\" runs just before the first code that needs it\nand runs at most once per request.\n\nIn the current implementation, the scope sharing is done with closures, so variables will only\nbe shared if they are visible at compile-time in the other parts of the component. In addition,\nyou can't rely on the specific destruction time of the shared variables, because they may not be\ndestroyed until the first time the \"<%shared>\" section executes in a future request. \"<%init>\"\noffers a more predictable execution and destruction time.\n\nCurrently any component with a \"<%shared>\" section incurs an extra performance penalty, because\nMason must recreate its anonymous subroutines the first time each new request uses the\ncomponent. The exact penalty varies between systems and for most applications will be\nunnoticeable. However, one should avoid using \"<%shared>\" when patently unnecessary, e.g. when\nan \"<%init>\" would work just as well.\n\nDo not attempt to \"return()\" from a \"<%shared>\" section; the current compiler cannot properly\nhandle it.\n",
                "subsections": []
            },
            "EMBEDDED COMPONENTS": {
                "content": "<%def *name*>\nEach instance of this section creates a *subcomponent* embedded inside the current component.\nInside you may place anything that a regular component contains, with the exception of \"<%def>\",\n\"<%method>\", \"<%once>\", and \"<%shared>\" tags.\n\nThe *name* consists of characters in the set \"[\\w.-]\". To call a subcomponent simply use its\nname in <& &> or \"$m->comp\". A subcomponent can only be seen from the surrounding component.\n\nIf you define a subcomponent with the same name as a file-based component in the current\ndirectory, the subcomponent takes precedence. You would need to use an absolute path to call the\nfile-based component. To avoid this situation and for general clarity, we recommend that you\npick a unique way to name all of your subcomponents that is unlikely to interfere with\nfile-based components. A commonly accepted practice is to start subcomponent names with \".\".\n\nWhile inside a subcomponent, you may use absolute or relative paths to call file-based\ncomponents and also call any of your \"sibling\" subcomponents.\n\nThe lexical scope of a subcomponent is separate from the main component. However a subcomponent\ncan declare its own \"<%args>\" section and have relevant values passed in. You can also use a\n\"<%shared>\" section to declare variables visible from both scopes.\n\nIn the following example, we create a \".link\" subcomponent to produce a standardized hyperlink:\n\n<%def .link>\n<a href=\"http://www.<% $site %>.com\"><% $label %></a>\n\n<%args>\n$site\n$label=>ucfirst($site)\n</%args>\n</%def>\n\nVisit these sites:\n<ul>\n<li><& .link, site=>'yahoo' &></li>\n<li><& .link, site=>'cmp', label=>'CMP Media' &></li>\n<li><& .link, site=>'excite' &></li>\n</ul>\n\n<%method *name*>\nEach instance of this section creates a *method* embedded inside the current component. Methods\nresemble subcomponents in terms of naming, contents, and scope. However, while subcomponents can\nonly be seen from the parent component, methods are meant to be called from other components.\n\nThere are two ways to call a method. First, via a path of the form \"comp:method\":\n\n<& /foo/bar:method1 &>\n\n$m->comp('/foo/bar:method1');\n\nSecond, via the callmethod component method:\n\nmy $comp = $m->fetchcomp('/foo/bar');\n...\n$comp->callmethod('method1');\n\nMethods are commonly used in conjunction with autohandlers to make templates more flexible. See\nObject-Oriented Techniques for more information.\n\nYou cannot create a subcomponent and method with the same name. This is mostly to prevent\nobfuscation and accidental errors.\n",
                "subsections": []
            },
            "FLAGS AND ATTRIBUTES": {
                "content": "The \"<%flags>\" and \"<%attr>\" sections consist of key/value pairs, one per line, joined by '=>'.\nIn each pair, the key must be any valid Perl \"bareword identifier\" (made of letters, numbers,\nand the underscore character), and the value may be any scalar value, including references. An\noptional comment may follow each line.\n\n<%flags>\nUse this section to set official Mason flags that affect the current component's behavior.\n\nCurrently there is only one flag, \"inherit\", which specifies the component's *parent* in the\nform of a relative or absolute component path. A component inherits methods and attributes from\nits parent; see Object-Oriented Techniques for examples.\n\n<%flags>\ninherit=>'/sitehandler'\n</%flags>\n\n<%attr>\nUse this section to assign static key/value attributes that can be queried from other\ncomponents.\n\n<%attr>\ncolor => 'blue'\nfonts => [qw(arial geneva helvetica)]\n</%attr>\n\nTo query an attribute of a component, use the \"attr\" method:\n\nmy $color = $comp->attr('color')\n\nwhere $comp is a component object.\n\nMason evaluates attribute values once when loading the component. This makes them faster but\nless flexible than methods.\n",
                "subsections": []
            },
            "FILTERING": {
                "content": "This section describes several ways to apply filtering functions over the results of the current\ncomponent. By separating out and hiding a filter that, say, changes HTML in a complex way, we\nallow non-programmers to work in a cleaner HTML environment.\n\n<%filter> section\nThe \"<%filter>\" section allows you to arbitrarily filter the output of the current component.\nUpon entry to this code, $ contains the component output, and you are expected to modify it in\nplace. The code has access to component arguments and can invoke subroutines, call other\ncomponents, etc.\n\nThis simple filter converts the component output to UPPERCASE:\n\n<%filter>\ntr/a-z/A-Z/\n</%filter>\n\nThe following navigation bar uses a filter to \"unlink\" and highlight the item corresponding to\nthe current page:\n\n<a href=\"/\">Home</a> | <a href=\"/products/\">Products</a> |\n<a href=\"/bg.html\">Background</a> | <a href=\"/finance/\">Financials</a> |\n<a href=\"/support/\">Tech Support</a> | <a href=\"/contact.html\">Contact Us</a>\n\n<%filter>\nmy $uri = $r->uri;\ns{<a href=\"$uri/?\">(.*?)</a>} {<b>$1</b>}i;\n</%filter>\n\nThis allows a designer to code such a navigation bar intuitively without \"if\" statements\nsurrounding each link! Note that the regular expression need not be very robust as long as you\nhave control over what will appear in the body.\n\nA filter block does not have access to variables declared in a component's \"<%init>\" section,\nthough variables declared in the \"<%args>\", \"<%once>\" or \"<%shared>\" blocks are usable in a\nfilter.\n\nIt should be noted that a filter cannot rely on receiving all of a component's output at once,\nand so may be called multiple times with different chunks of output. This can happen if\nautoflush is on, or if a filter-containing component, or the components it calls, call the\n\"$m->flushbuffer()\" method.\n\nYou should never call Perl's \"return()\" function inside a filter section, or you will not see\nany output at all.\n\nYou can use Component Calls with Content if you want to filter specific parts of a component\nrather than the entire component.\n",
                "subsections": []
            },
            "COMMENT MARKERS": {
                "content": "There are several ways to place comments in components, i.e. arbitrary text that is ignored by\nthe parser.\n\n<%doc>\nText in this section is treated as a comment and ignored. Most useful for a component's main\ndocumentation. One can easily write a program to sift through a set of components and pull out\ntheir \"<%doc>\" blocks to form a reference page.\n\n<% # comment... %>\nA \"<% %>\" tag is considered a comment if all of its lines are either whitespace, or begin with a\n'#' optionally preceded by whitespace. For example,\n\n<% # This is a single-line comment %>\n\n<%\n# This is a\n# multi-line comment\n%>\n\n%# comment\nBecause a line beginning with \"%\" is treated as Perl, \"%#\" automatically works as a comment.\nHowever we prefer the \"<% # comment %>\" form over \"%#\", because it stands out a little more as a\ncomment and because it is more flexible with regards to preceding whitespace.\n\n% if (0) { }\nAnything between these two lines\n\n% if (0) {\n...\n% }\n\nwill be skipped by Mason, including component calls. While we don't recommend this for comments\nper se, it is a useful notation for \"commenting out\" code that you don't want to run.\n\nHTML/XML/... comments\nHTML and other markup languages will have their own comment markers, for example \"<!-- -->\".\nNote two important differences with these comments versus the above comments:\n\n*   They will be sent to the client and appear in the source of the page.\n\n*   They do not block component calls and other code from running, so don't try to use them to\ncomment out code!\n\n<!-- Oops, the code below will still run\n<& /shared/expensive.mhtml &>\n-->\n",
                "subsections": []
            },
            "OTHER SYNTAX": {
                "content": "<%text>\nText in this section is printed as-is with all Mason syntax ignored. This is useful, for\nexample, when documenting Mason itself from a component:\n\n<%text>\n% This is an example of a Perl line.\n<% This is an example of an expression block. %>\n</%text>\n\nThis works for almost everything, but doesn't let you output \"</%text>\" itself! When all else\nfails, use \"$m->print\":\n\n% $m->print('The tags are <%text> and </%text>.');\n",
                "subsections": [
                    {
                        "name": "Escaping expressions",
                        "content": "Mason has facilities for *escaping* the output from \"<% %>\" tags, on either a site-wide or a\nper-expression basis.\n\nAny \"<% %>\" expression may be terminated by a '|' and one or more escape flags (plus arbitrary\nwhitespace), separated by commas:\n\n<% $filedata |h %>\n\nThe current valid flags are:\n\n*   h\n\nEscape HTML ('<' => '&lt;', etc.) using \"HTML::Entities::encode()\". Before Perl 5.8.0 this\nmodule assumes that text is in the ISO-8859-1 character set; see the next section for how to\noverride this escaping. After 5.8.0, the encoding assumes that text is in Unicode.\n\n*   u\n\nEscape a URL query string (':' => '%3A', etc.) - all but [a-zA-Z0-9.-]\n\n*   n\n\nThis is a special flag indicating that the default escape flags should *not* be used for\nthis substitution.\n\nThe administrator may specify a set of default escape flags via the defaultescapeflags\nparameter. For example, if the administrator sets defaultescapeflags to \"['h']\", then all <%\n%> expressions will automatically be HTML-escaped. In this case you would use the \"n\" flag to\nturn off HTML-escaping for a specific expression:\n\n<% $htmlblock |n %>\n\nMultiple escapes can be specified as a comma-separated list:\n\n<% $uri | u, n %>\n\nThe old pre-defined escapes, 'h', 'u', and 'n', can be used *without* commas, so that this is\nlegal:\n\n<% $uri | un %>\n\nHowever, this only works for these three escapes, and no others. If you are using user-defined\nescapes as well, you *must* use a comma:\n\n<% $uri | u, addsession %>\n\nUser-defined Escapes\nBesides the default escapes mentioned above, it is possible for the user to define their own\nescapes or to override the built-in 'h' and 'u' escapes.\n\nThis is done via the Interp object's escapeflags parameter or setescape() method. Escape names\nmay be any number of characters as long as it matches the regex \"/^[\\w-]+$/\". The one exception\nis that you cannot override the 'n' flag.\n\nEach escape flag is associated with a subroutine reference. The subroutine should expect to\nreceive a scalar reference, which should be manipulated in place. Any return value from this\nsubroutine is ignored.\n\nEscapes can be defined at any time but using an escape that is not defined will cause an error\nwhen executing that component.\n\nA common use for this feature is to override the built-in HTML escaping, which will not work\nwith non-ISO-8559-1 encodings. If you are using such an encoding and want to switch the 'h' flag\nto do escape just the minimal set of characters (\"<\", \">\", \"&\", \"\"\"), put this in your Apache\nconfiguration:\n\nPerlSetVar  MasonEscapeFlags  \"h => \\&HTML::Mason::Escapes::basichtmlescape\"\n\nOr, in a top-level autohandler:\n\n$m->interp->setescape( h => \\&HTML::Mason::Escapes::basichtmlescape );\n\nOr you could write your own escape function for a particular encoding:\n\n$ah->interp->setescape( h => \\&myhtmlescape );\n\nAnd of course this can be used for all sorts of other things, like a naughty words filter for\nthe easily offended:\n\n$interp->setescape( 'no-naughty' => \\&removenaughtywords );\n\nManually applying escapes\nYou can manually apply one or more escapes to text using the Interp object's \"applyescapes()\"\nmethod. e.g.\n\n$m->interp->applyescapes( 'some html content', 'h' );\n"
                    },
                    {
                        "name": "Backslash at end of line",
                        "content": "A backslash (\\) at the end of a line suppresses the newline. In HTML components, this is mostly\nuseful for fixed width areas like \"<pre>\" tags, since browsers ignore white space for the most\npart. An example:\n\n<pre>\nfoo\n% if (1) {\nbar\n% }\nbaz\n</pre>\n\noutputs\n\nfoo\nbar\nbaz\n\nbecause of the newlines on lines 2 and 4. (Lines 3 and 5 do not generate a newline because the\nentire line is taken by Perl.) To suppress the newlines:\n\n<pre>\nfoo\\\n% if (1) {\nbar\\\n% }\nbaz\n</pre>\n\nwhich prints\n\nfoobarbaz\n"
                    }
                ]
            },
            "DATA CACHING": {
                "content": "Mason's data caching interface allows components to cache the results of computation for\nimproved performance. Anything may be cached, from a block of HTML to a complex data structure.\n\nEach component gets its own private, persistent data cache. Except under special circumstances,\none component does not access another component's cache. Each cached value may be set to expire\nat a certain time.\n\nData caching is implemented on top of one of two external caching APIs: \"Cache::Cache\", which is\nstable but has not changed in years, or \"CHI\", which has picked up where \"Cache::Cache\" has left\noff and is actively maintained. You control which one Mason uses with the datacacheapi\nparameter. \"Cache::Cache\" is the default for backward compatibility reasons, but we recommend\n\"CHI\" for anyone doing serious caching. The APIs are very similar for Mason users, so that most\nof the information below applies to both; any differences are noted.\n",
                "subsections": [
                    {
                        "name": "Basic Usage",
                        "content": "The \"$m->cache\" method returns a cache object representing the cache for this component. Here's\nthe typical usage of \"$m->cache\":\n\nmy $result = $m->cache->get('key');\nif (!defined($result)) {\n... compute $result ...\n$m->cache->set('key', $result);\n}\n\n\"$m->cache->get\" attempts to retrieve this component's cache value. If the value is available it\nis placed in $result. If the value is not available, $result is computed and stored in the cache\nby \"$m->cache->set\".\n\nMultiple Keys/Values\nA cache can store multiple key/value pairs. A value can be anything serializable by \"Storable\",\nfrom a simple scalar to an arbitrary complex list or hash reference:\n\n$m->cache->set(name => $string);\n$m->cache->set(friends => \\@list);\n$m->cache->set(map => \\%hash);\n\nYou can fetch all the keys in a cache with\n\nmy @idents = $m->cache->getkeys;\n\nIt should be noted that Mason reserves all keys beginning with \"mason\" for its own use.\n"
                    },
                    {
                        "name": "Expiration",
                        "content": "You can pass an optional third argument to \"$m->cache->set\" indicating when the item should\nexpire:\n\n$m->cache->set('name1', $string1, '5 min');  # Expire in 5 minutes\n$m->cache->set('name2', $string2, '3h');     # Expire in 3 hours\n\nTo change the expiration time for a piece of data, call \"set\" again with the new expiration. To\nexpire an item immediately, use \"$m->cache->remove\".\n\nYou can also specify an expiration condition when you fetch the item, using the *expireif*\noption:\n\nmy $result = $m->cache->get('key',\nexpireif=>sub { $[0]->getcreatedat < (stat($file))[9] });\n\n*expireif* takes an anonymous subroutine, which is called with the cache object as its only\nparameter. If the subroutine returns a true value, the item is expired. In the example above, we\nexpire the item whenever a certain file changes.\n\nFinally, you can expire a cache item from an external script; see Accessing a Cache Externally\nbelow.\n"
                    },
                    {
                        "name": "Avoiding Concurrent Recomputation",
                        "content": "The code shown in \"Basic Usage\" above,\n\nmy $result = $m->cache->get('key');\nif (!defined($result)) {\n... compute $result ...\n$m->cache->set('key', $result);\n}\n\ncan suffer from a kind of race condition for caches that are accessed frequently and take a long\ntime to recompute.\n\nSuppose that a particular cache value is accessed five times a second and takes three seconds to\nrecompute. When the cache expires, the first process comes in, sees that it is expired, and\nstarts to recompute the value. The second process comes in and does the same thing. This\nsequence continues until the first process finishes and stores the new value. On average, the\nvalue will be recomputed and written to the cache 15 times!\n\nOne solution is the *busylock* flag:\n\nmy $result = $m->cache->get('key', busylock=>'30 sec');\n\nIn this case, when the value cannot be retrieved, \"get()\" sets the expiration time of the value\n30 seconds in the future before returning \"undef\". This tells the first process to compute the\nnew value while causing subsequent processes to use the old value for 30 seconds.\n\nShould the 30 seconds expire before the first process is done, a second process will start\ncomputing the new value while setting the expiration time yet another 30 seconds in the future,\nand so on.\n\nThe disadvantage of this solution is that multiple writes to the cache will be performed for\neach \"set()\".\n\nAnother solution, available only if you are using \"CHI\", is \"expiresvariance\" which will create\na variable time window during which expiration may occur. See the \"CHI\" documentation for\ndetails.\n"
                    },
                    {
                        "name": "Caching All Output",
                        "content": "Occasionally you will need to cache the complete output of a component. For this purpose, Mason\noffers the \"$m->cacheself\" method. This method causes Mason to check to see if this component\nhas already been run and its output cached. If this is the case, this output is simply sent as\noutput. Otherwise, the component run normally and its output and return value cached.\n\nIt is typically used right at the top of an \"<%init>\" section:\n\n<%init>\nreturn if $m->cacheself(key => 'fookey', expiresin => '3 hours',\n... <other cache options> ...);\n... <rest of init> ...\n</%init>\n\nA full list of parameters and examples are available in the cacheself section of the Request\nmanual.\n"
                    },
                    {
                        "name": "Cache Object",
                        "content": "\"$m->cache->getobject\" returns a \"Cache::Object\" or \"CHI::CacheObject\" associated with a\nparticular key. You can use this to retrieve useful meta-data:\n\nmy $co = $m->cache->getobject('name1');\n$co->getcreatedat();    # when was object stored in cache\n$co->getexpiresat();    # when does object expire\n"
                    },
                    {
                        "name": "Choosing a Cache Subclass - with Cache::Cache",
                        "content": "The \"Cache::Cache\" API is implemented by a variety of backend subclasses. For example,\n\"FileCache\" implements the interface with a set of directories and files, \"MemoryCache\"\nimplements the interface in process memory, and \"SharedMemoryCache\" implements the interface in\nshared memory.\n\nBy default \"$m->cache\" uses \"FileCache\", but you can override this with the *cacheclass*\nkeyword. The value must be the name of a \"Cache::Cache\" subclass; the prefix \"Cache::\" need not\nbe included. For example:\n\nmy $result = $m->cache(cacheclass => 'MemoryCache')->get('key');\n$m->cache(cacheclass => 'MemoryCache')->set(key => $result);\n\nYou can even specify different subclasses for different keys in the same component. Just make\nsure the correct value is passed to all calls to \"$m->cache\"; Mason does not remember which\nsubclass you have used for a given component or key.\n\nThe administrator can set the default cache subclass used by all components with the\ndatacachedefaults parameter.\n"
                    },
                    {
                        "name": "Choosing a Cache Subclass - with CHI",
                        "content": "The \"CHI\" API is implemented by a variety of drivers, for example \"CHI::Driver::File\",\n\"CHI::Driver::FastMmap\", and \"CHI::Driver::Memcached\".\n\n\"CHI::Driver::File\" is the default, but you can override this with the *driver* keyword. The\nvalue must be the name of a \"CHI::Driver\" subclass; the prefix \"CHI::Driver::\" need not be\nincluded. For example:\n\nmy $cache = $m->cache(driver => 'Memcached', servers => [ ... ]);\nmy $result = $cache->get('key');\n$cache->set(key => $result);\n\nYou can even specify different subclasses for different keys in the same component. Just make\nsure the correct value is passed to all calls to \"$m->cache\"; Mason does not remember which\nsubclass you have used for a given component or key.\n\nThe administrator can set the default cache subclass used by all components with the\ndatacachedefaults parameter.\n"
                    },
                    {
                        "name": "Accessing a Cache Externally",
                        "content": "To access a component's cache from outside the component (e.g. in an external Perl script),\nyou'll need have the following information:\n\n*   the namespace associated with the component. For \"Cache::Cache\", the function\n\"HTML::Mason::Utils::datacachenamespace\", given a component id (usually just the component\npath), returns the namespace. For \"CHI\", the component id/path itself is the namespace.\n\n*   the cacheroot, for file-based caches only. Defaults to the \"cache\" subdirectory under the\nMason data directory.\n\nGiven this information you can get a handle on the component's cache. For example, the following\ncode removes a cache item for component /foo/bar, assuming the data directory is\n/usr/local/www/mason and you are using the default file backend:\n\nuse HTML::Mason::Utils qw(datacachenamespace);\n\n# With Cache::Cache\nmy $cache = new Cache::FileCache\n( { namespace => datacachenamespace(\"/foo/bar\"),\ncacheroot => \"/usr/local/www/mason/cache\" } );\n\n# With CHI\nmy $cache = CHI->new\n( driver => 'File',\nnamespace => \"/foo/bar\",\ncacheroot => \"/usr/local/www/mason/cache\" );\n\n# Remove one key\n$cache->remove('key1');\n\n# Remove all keys\n$cache->clear;\n"
                    },
                    {
                        "name": "Mason 1.0x Cache API",
                        "content": "For users upgrading from 1.0x and earlier, any existing $m->cache code will be incompatible with\nthe new API. However, if you wish to continue using the 1.0x cache API for a while, you (or your\nadministrator) can set datacacheapi to '1.0'. All of the $m->cache options with the exception\nof \"tieclass\" should be supported.\n\nThe \"accessdatacache\" function is no longer available; this will need to be converted to use\n\"Cache::Cache\" directly, as described in the previous section.\n"
                    }
                ]
            },
            "WEB-SPECIFIC FEATURES": {
                "content": "",
                "subsections": [
                    {
                        "name": "Sending HTTP Headers",
                        "content": "Mason automatically sends HTTP headers via \"$r->sendhttpheader\" but it will not send headers\nif they've already been sent manually.\n\nTo determine the exact header behavior on your system, you need to know whether your server's\ndefault is to have autoflush on or off. Your administrator should have this information. If your\nadministrator doesn't know then it is probably off, the default.\n\nWith autoflush off the header situation is extremely simple: Mason waits until the very end of\nthe request to send headers. Any component can modify or augment the headers.\n\nWith autoflush on the header situation is more complex. Mason will send headers just before\nsending the first output. This means that if you want to affect the headers with autoflush on,\nyou must do so before any component sends any output. Generally this takes place in an \"<%init>\"\nsection.\n\nFor example, the following top-level component calls another component to see whether the user\nhas a cookie; if not, it inserts a new cookie into the header.\n\n<%init>\nmy $cookie = $m->comp('/shared/getusercookie');\nif (!$cookie) {\n$cookie = new CGI::Cookie (...);\n$r->headerout('Set-cookie' => $cookie);\n}\n...\n</%init>\n\nWith autoflush off this code will always work. Turn autoflush on and this code will only work as\nlong as /shared/getusercookie doesn't output anything (given its functional nature, it\nshouldn't).\n\nThe administrator can turn off automatic header sending via the autosendheaders parameter. You\ncan also turn it off on individual pages with\n\n$m->autosendheaders(0);\n"
                    },
                    {
                        "name": "Returning HTTP Status",
                        "content": "The value returned from the top-most component becomes the status code of the request. If no\nvalue is explicitly returned, it defaults to OK (0).\n\nSimply returning an error status (such as 404) from the top-most component has two problems in\npractice. First, the decision to return an error status often resides further down in the\ncomponent stack. Second, you may have generated some content by the time this decision is made.\n(Both of these are more likely to be true when using autohandlers.)\n\nThus the safer way to generate an error status is\n\n$m->clearbuffer;\n$m->abort($status);\n\n\"$m->abort\" bypasses the component stack and ensures that $status is returned from the top-most\ncomponent. It works by throwing an exception. If you wrapped this code (directly or indirectly)\nin an eval, you must take care to rethrow the exception, or the status will not make it out:\n\neval { $m->comp('...') };\nif (my $err = $@) {\nif ($m->aborted) {\ndie $err;\n} else {\n# deal with non-abort exceptions\n}\n}\n\nFilters and $m->abort\nA filter section will still be called after a component aborts with \"$m->abort\". You can always\ncheck \"$m->aborted\" in your \"<%filter>\" block if you don't want to run the filter after an\nabort.\n\n<%filter>\nunless ( $m->aborted ) {\n$ .= ' filter stuff';\n}\n</%filter>\n"
                    },
                    {
                        "name": "External Redirects",
                        "content": "Because it is so commonly needed, Mason 1.1x and on provides an external redirect method:\n\n$m->redirect($url);    # Redirects with 302 status\n\nThis method uses the clearbuffer/abort technique mentioned above, so the same warnings apply\nregarding evals.\n\nAlso, if you generate any output *after* calling \"$m->redirect\", then this output will be sent,\nand will break the redirect. For example:\n\n% eval { $m->comp('redirect', ...) };\n\n% die $@ if $@;\n\nThe blank line between the two Perl lines is new output generated after the redirect. Either\nremove it or call \"$m->clearbuffer\" immediately before calling \"die()\".\n"
                    },
                    {
                        "name": "Internal Redirects",
                        "content": "There are two ways to perform redirects that are invisible to the client.\n\nFirst, you can use a Mason subrequest (see \"Subrequests\"). This only works if you are\nredirecting to another Mason page.\n\nSecond, you can use Apache's internalredirect method, which works whether or not the new URL\nwill be handled by Mason. Use it this way:\n\n$r->internalredirect($url);\n$m->autosendheaders(0);\n$m->clearbuffer;\n$m->abort;\n\nThe last three lines prevent the original request from accidentally generating extra headers or\ncontent.\n"
                    }
                ]
            },
            "USING THE PERL DEBUGGER": {
                "content": "You can use the perl debugger in conjunction with a live modperl/Mason server with the help of\nApache::DB, available from CPAN. Refer to the Apache::DB documentation for details.\n\nThe only tricky thing about debugging Mason pages is that components are implemented by\nanonymous subroutines, which are not easily breakpoint'able. To remedy this, Mason calls the\ndummy subroutine \"debughook\" at the beginning of each component. You can breakpoint this\nsubroutine like so:\n\nb HTML::Mason::Request::debughook\n\ndebughook is called with two parameters: the current Request object and the full component\npath. Thus you can breakpoint specific components using a conditional on $[1]:\n\nb HTML::Mason::Request::debughook $[1] =~ /component name/\n\nYou can avoid all that typing by adding the following to your ~/.perldb file:\n\n# Perl debugger aliases for Mason\n$DB::alias{mb} = 's/^mb\\b/b HTML::Mason::Request::debughook/';\n\nwhich reduces the previous examples to just:\n\nmb\nmb $[1] =~ /component name/\n\nMason normally inserts '#line' directives into compiled components so that line numbers are\nreported relative to the source file. Depending on your task, this can be a help or a hindrance\nwhen using the debugger. The administrator can turn off '#line' directives with the\nusesourcelinenumbers parameter.\n",
                "subsections": []
            },
            "LOGGING": {
                "content": "Mason uses \"Log::Any\" to log various events, such as the start and end of each request and each\ncomponent call. You can also log to \"Log::Any\" from a component with the \"$m->log\" method. e.g.\n\n$m->log->error(\"Something bad happened!\");\n$m->log->debugf(\"Arguments for '%s' were '%s'\", $func, \\%args)\nif $m->log->isdebug;\n\nSee \"Log::Any::Adapter\" for how to direct these logs to an output of your choice.\n",
                "subsections": []
            },
            "OBJECT-ORIENTED TECHNIQUES": {
                "content": "Earlier you learned how to assign a common template to an entire hierarchy of pages using\n*autohandlers*. The basic template looks like:\n\nheader HTML\n% $m->callnext;\nfooter HTML\n\nHowever, sometimes you'll want a more flexible template that adjusts to the requested page. You\nmight want to allow each page or subsection to specify a title, background color, or logo image\nwhile leaving the rest of the template intact. You might want some pages or subsections to use a\ndifferent template, or to ignore templates entirely.\n\nThese issues can be addressed with the object-oriented style primitives introduced in Mason\n0.85.\n\nNote: we use the term object-oriented loosely. Mason borrows concepts like inheritance, methods,\nand attributes from object methodology but implements them in a shallow way to solve a\nparticular set of problems. Future redesigns may incorporate a deeper object architecture if the\ncurrent prototype proves successful.\n",
                "subsections": [
                    {
                        "name": "Determining inheritance",
                        "content": "Every component may have a single *parent*. The default parent is a component named\n\"autohandler\" in the closest parent directory. This rule applies to autohandlers too: an\nautohandler may not have itself as a parent but may have an autohandler further up the tree as\nits parent.\n\nYou can use the \"inherit\" flag to override a component's parent:\n\n<%flags>\ninherit => '/foo/bar'\n</%flags>\n\nIf you specify undef as the parent, then the component inherits from no one. This is how to\nsuppress templates.\n\nCurrently there is no way to specify a parent dynamically at run-time, or to specify multiple\nparents.\n"
                    },
                    {
                        "name": "Content wrapping",
                        "content": "At page execution time, Mason builds a chain of components from the called component, its\nparent, its parent's parent, and so on. Execution begins with the top-most component; calling\n\"$m->callnext\" passes control to the next component in the chain. This is the familiar\nautohandler \"wrapping\" behavior, generalized for any number of arbitrarily named templates.\n"
                    },
                    {
                        "name": "Accessing methods and attributes",
                        "content": "A template can access methods and/or attributes of the requested page. First, use\n\"$m->requestcomp\" to get a handle on the appropriate component:\n\nmy $self = $m->requestcomp;\n\n$self now refers to the component corresponding to the requested page (the component at the end\nof the chain).\n\nTo access a method for the page, use \"callmethod\":\n\n$self->callmethod('header');\n\nThis looks for a method named 'header' in the page component. If no such method exists, the\nchain of parents is searched upwards, until ultimately a \"method not found\" error occurs. Use\n'methodexists' to avoid this error for questionable method calls:\n\nif ($self->methodexists('header')) { ...\n\nThe component returned by the \"$m->requestcomp\" method never changes during request execution.\nIn contrast, the component returned by \"$m->basecomp\" may change several times during request\nexecution.\n\nWhen execution starts, the base component is the same as the requested component. Whenever a\ncomponent call is executed, the base component may become the component that was called. The\nbase component will change for all component calls except in the following cases:\n\n*   A component is called via its component object rather than its path, for example:\n\n<& $m->fetchcomp('/some/comp'), foo => 1 &>\n\n*   A subcomponent (defined with \"<%def>\") is called.\n\n*   A method is called via the use of \"SELF:\", \"PARENT:\", or \"REQUEST:\". These are covered in\nmore detail below.\n\nIn all other cases, the base component is the called component or the called component's owner\ncomponent if that called component is a method.\n\nAs hinted at above, Mason provides a shortcut syntax for method calls.\n\nIf a component call path starts with \"SELF:\", then Mason will start looking for the method (the\nportion of the call after \"SELF:\"), in the base component.\n\n<& SELF:header &>\n$m->comp('SELF:header')\n\nIf the call path starts with \"PARENT:\", then Mason will start looking in the current component's\nparent for the named method.\n\n<& PARENT:header &>\n$m->comp('PARENT:header')\n\nIn the context of a component path, PARENT is shorthand for \"$m->currentcomp->parent\".\n\nIf the call path begins with \"REQUEST:\", then Mason looks for the method in the requested\ncomponent. REQUEST is shorthand for \"$m->requestcomp\".\n\nThe rules for attributes are similar. To access an attribute for the page, use \"attr\":\n\nmy $color = $self->attr('color')\n\nThis looks for an attribute named 'color' in the $self component. If no such attribute exists,\nthe chain of parents is searched upwards, until ultimately an \"attribute not found\" error\noccurs. Use \"attrexists\" or \"attrifexist\" to avoid this error for questionable attributes:\n\nif ($self->attrexists('color')) { ...\n\nmy $color = $self->attrifexists('color'); # if it doesn't exist $color is undef\n"
                    },
                    {
                        "name": "Sharing data",
                        "content": "A component's main body and its methods occupy separate lexical scopes. Variables declared, say,\nin the \"<%init>\" section of the main component cannot be seen from methods.\n\nTo share variables, declare them either in the \"<%once>\" or \"<%shared>\" section. Both sections\nhave an all-inclusive scope. The \"<%once>\" section runs once when the component loads; its\nvariables are persistent for the lifetime of the component. The \"<%shared>\" section runs once\nper request (when needed), just before any code in the component runs; its variables last only\ntil the end of the request.\n\nIn the following example, various sections of code require information about the logged-in user.\nWe use a \"<%shared>\" section to fetch these in a single request.\n\n<%attr>\ntitle=>sub { \"Account for $fullname\" }\n</%attr>\n\n<%method lefttoc>\n<i><% $fullname %></i>\n(<a href=\"logout.html\">Log out</a>)<br />\n...\n</%method>\n\nWelcome, <% $fname %>. Here are your options:\n\n<%shared>\nmy $dbh = DBI::connect ...;\nmy $user = $r->connection->user;\nmy $sth = $dbh->prepare(\"select lname,fname, from users where userid = ?\");\n$sth->execute($user);\nmy ($lname, $fname) = $sth->fetchrowarray;\nmy $fullname = \"$first $last\";\n</%shared>\n\n\"<%shared>\" presents a good alternative to \"<%init>\" when data is needed across multiple scopes.\nOutside these situations, \"<%init>\" is preferred for its slightly greater speed and predictable\nexecution model.\n"
                    },
                    {
                        "name": "Example",
                        "content": "Let's say we have three components:\n\n/autohandler\n/products/autohandler\n/products/index.html\n\nand that a request comes in for /products/index.html.\n\n/autohandler contains a general template for the site, referring to a number of standard methods\nand attributes for each page:\n\n<head>\n<title><& SELF:title &></title>\n</head>\n<body style=\"<% $self->attr('bodystyle') %>\">\n<& SELF:header &>\n\n<div id=\"main\">\n% $m->callnext;\n</div>\n\n<& SELF:footer &>\n</body>\n\n<%init>\nmy $self = $m->basecomp;\n...\n</%init>\n\n<%attr>\nbodystyle => 'standard'\n</%attr>\n\n<%method title>\nMcGuffey Inc.\n</%method>\n\n<%method header>\n<h2><& SELF:title &></h2>\n</%method>\n\n<%method footer>\n</%method>\n\nNotice how we provide defaults for each method and attribute, even if blank.\n\n/products/autohandler overrides some attributes and methods for the /products section of the\nsite.\n\n<%attr>\nbodystyle => 'plain'\n</%attr>\n<%method title>\nMcGuffey Inc.: Products\n</%method>\n\n% $m->callnext;\n\nNote that this component, though it only defines attributes and methods, must call\n\"$m->callnext\" if it wants the rest of the chain to run.\n\n/products/index.html might override a few attributes, but mainly provides a primary section for\nthe body.\n"
                    }
                ]
            },
            "COMMON TRAPS": {
                "content": "Do not call $r->content or \"new CGI\"\nMason calls \"$r->content\" itself to read request input, emptying the input buffer and\nleaving a trap for the unwary: subsequent calls to \"$r->content\" hang the server. This is a\nmodperl \"feature\" that may be fixed in an upcoming release.\n\nFor the same reason you should not create a CGI object like\n\nmy $query = new CGI;\n\nwhen handling a POST; the CGI module will try to reread request input and hang. Instead,\ncreate an empty object:\n\nmy $query = new CGI (\"\");\n\nsuch an object can still be used for all of CGI's useful HTML output functions. Or, if you\nreally want to use CGI's input functions, initialize the object from %ARGS:\n\nmy $query = new CGI (\\%ARGS);\n",
                "subsections": []
            },
            "MASON AND SOURCE FILTERS": {
                "content": "Modules which work as source filters, such as \"Switch.pm\", will only work when you are using\nobject files. This is because of how source filters are implemented, and cannot be changed by\nthe Mason authors.\n",
                "subsections": []
            }
        }
    }
}