NAME
Template::Flute - Modern designer-friendly HTML templating Engine
VERSION
Version 0.0103
SYNOPSIS
use Template::Flute;
my ($cart, $flute, %values);
$cart = [{...},{...}];
$values{cost} = ...
$flute = new Template::Flute(specification_file => 'cart.xml',
template_file => 'cart.html',
iterators => {cart => $cart},
values => \%values,
);
print $flute->process();
DESCRIPTION
Template::Flute enables you to completely separate web design and programming tasks for dynamic web applications.
Templates are designed to be designer-friendly; there's no inline code or mini templating language for your designers to learn - instead, standard HTML and CSS classes are used, leading to HTML that can easily be understood and edited by WYSIWYG editors and hand-coding designers alike.
An example is easier than a wordy description:
Given the following template snippet:
<div class="customer_name">Mr A Test</div>
<div class="customer_email">someone@example.com</div>
and the following specification:
<specification name="example" description="Example">
<value name="customer_name" />
<value name="email" class="customer_email" />
</specification>
Processing the above as follows:
$flute = Template::Flute->new(
template_file => 'template.html',
specification_file => 'spec.xml',
);
$flute->set_values({
customer_name => 'Bob McTest',
email => 'bob@example.com',
});;
print $flute->process;
The resulting output would be:
<div class="customer_name">Bob McTest</div>
<div class="email">bob@example.com</div>
In other words, rather than including a templating language within your templates which your designers must master and which could interfere with previews in WYSWYG tools, CSS selectors in the template are tied to your data structures or objects by a specification provided by the programmer.
Workflow
The easiest way to use Template::Flute is to pass all necessary parameters to the constructor and call the process method to generate the HTML.
You can also break it down in separate steps:
- 1. Parse specification
-
Parse specification based on your specification format (e.g with Template::Flute::Specification::XML or Template::Flute::Specification::Scoped.).
$xml_spec = new Template::Flute::Specification::XML; $spec = $xml_spec->parse(q{<specification name="cart" description="Cart"> <list name="cart" class="cartitem" iterator="cart"> <param name="name" field="title"/> <param name="quantity"/> <param name="price"/> </list> <value name="cost"/> </specification>});
- 2. Parse template
-
Parse template with Template::Flute::HTML object.
$template = new Template::Flute::HTML; $template->parse(q{<html> <head> <title>Cart Example</title> </head> <body> <table class="cart"> <tr class="cartheader"> <th>Name</th> <th>Quantity</th> <th>Price</th> </tr> <tr class="cartitem"> <td class="name">Sample Book</td> <td><input class="quantity" name="quantity" size="3" value="10"></td> <td class="price">$1</td> </tr> <tr class="cartheader"><th colspan="2"></th><th>Total</th> </tr> <tr> <td colspan="2"></td><td class="cost">$10</td> </tr> </table> </body></html>}, $spec);
- 3. Produce HTML output
-
$flute = new Template::Flute(template => $template, iterators => {cart => $cart}, values => {cost => '84.94'}); $flute->process();
CONSTRUCTOR
new
Create a Template::Flute object with the following parameters:
- specification_file
-
Specification file name.
- specification_parser
-
Select specification parser. This can be either the full class name like MyApp::Specification::Parser or the last part for classes residing in the Template::Flute::Specification namespace.
- specification
-
Specification object or specification as string.
- template_file
-
HTML template file.
- template
-
Template::Flute::HTML object or template as string.
- database
-
Template::Flute::Database::Rose object.
- filters
-
Hash reference of filter functions.
- i18n
-
Template::Flute::I18N object.
- iterators
-
Hash references of iterators.
- values
-
Hash reference of values to be used by the process method.
- auto_iterators
-
Builds iterators automatically from values.
METHODS
process [HASHREF]
Processes HTML template, manipulates the HTML tree based on the specification, values and iterators.
Returns HTML output.
process_template
Processes HTML template and returns Template::Flute::HTML object.
filter ELEMENT VALUE
Runs the filter used by ELEMENT on VALUE and returns the result.
value NAME
Returns the value for NAME.
set_values HASHREF
Sets hash reference of values to be used by the process method. Same as passing the hash reference as values argument to the constructor.
template
Returns HTML template object, see Template::Flute::HTML for details.
specification
Returns specification object, see Template::Flute::Specification for details.
SPECIFICATION
The specification ties the elements in the HTML template to the data (variables, lists, forms) which is added to the template.
The default format for the specification is XML implemented by the Template::Flute::Specification::XML module. You can use the Config::Scoped format implemented by Template::Flute::Specification::Scoped module or write your own specification parser class.
Possible elements in the specification are:
- container
-
The first container is only shown in the output if the value
billing_address
is set:<container name="billing" value="billing_address" class="billingWrapper"> </container>
The second container is shown if the value
warnings
or the valueerrors
is set:<container name="account_errors" value="warnings|errors" class="infobox"> <value name="warnings"/> <value name="errors"/> </container>
- list
- separator
-
Separator elements for list are added after any list item in the output with the exception of the last one.
Example specification, HTML template and output:
<specification> <list name="list" iterator="tokens"> <param name="key"/> <separator name="sep"/> </list> </specification> <div class="list"><span class="key">KEY</span></div><span class="sep"> | </span> <div class="list"><span class="key">FOO</span></div><span class="sep"> | </span> <div class="list"><span class="key">BAR</span></div>
- param
-
Param elements are replaced with the corresponding value from the list iterator.
The following operations are supported for param elements:
- append
-
Appends the param value to the text found in the HTML template.
- toggle
-
Without target attribute, it only shows corresponding HTML element if param value is set. Wiht target attribute, it simply toggles the target attribute.
Other attributes for param elements are:
- filter
-
Applies filter to param value.
- increment
-
Uses value from increment instead of a value from the iterator.
<param name="pos" increment="1">
- value
-
Value elements are replaced with a single value present in the values hash passed to the constructor of this class or later set with the set_values method.
The following operations are supported for value elements:
- append
-
Appends the value to the text found in the HTML template.
- hook
-
Insert HTML residing in value as subtree of the corresponding HTML element. HTML will be parsed with XML::Twig. See "INSERT HTML" for an example.
- toggle
-
Only shows corresponding HTML element if value is set.
Other attributes for value elements are:
- filter
-
Applies filter to value.
- include
-
Processes the template file named in this attribute. This implies the hook operation.
- form
-
Form elements are tied through specification to HTML forms. Attributes for form elements in addition to
class
andid
are:- link
-
The link attribute can only have the value
name
and allows to base the relationship between form specification elements and HTML form tags on the name HTML attribute instead ofclass
, which is usually more convenient.
- input
- filter
- sort
- i18n
SIMPLE OPERATORS
append
Appends the value to the text inside a HTML element or to an attribute if target
has been specified. This can be used in value
and param
specification elements.
The example shows how to add a HTML class to elements in a list:
HTML:
<ul class="nav-sub">
<li class="category"><a href="" class="catname">Medicine</a></li>
</ul>
XML:
<specification>
<list name="category" iterator="categories">
<param name="name" class="catname"/>
<param name="catname" field="uri" target="href"/>
<param name="css" class="catname" target="class" op="append" joiner=" "/>
</list>
</specification>
CONDITIONALS
Display image only if present
In this example we want to show an image only on a certain condition:
HTML:
<span class="banner-box">
<img class="banner" src=""/>
</span>
XML:
<container name="banner-box" value="banner">
<value name="banner" target="src"/>
</container>
Source code:
if ($organization eq 'Big One') {
$values{banner} = 'banners/big_one.png';
}
Display link in a list only if present
In this example we want so show a link only if an URL is available:
HTML:
<div class="linklist">
<span class="name">Name</span>
<div class="link">
<a href="#" class="url">Goto ...</a>
</div>
</div>
XML:
<specification name="link">
<list name="links" class="linklist" iterator="links">
<param name="name"/>
<param name="url" target="href"/>
<param name="link" field="url" op="toggle" args="tree"/>
</list>
</specification>
Source code:
@records = ({name => 'Link', url => 'http://localhost/'},
{name => 'No Link'},
{name => 'Another Link', url => 'http://localhost/'},
);
$flute = Template::Flute->new(specification => $spec_xml,
template => $template,
iterators => {links => \@records});
$output = $flute->process();
ITERATORS
Template::Flute uses iterators to retrieve list elements and insert them into the document tree. This abstraction relieves us from worrying about where the data actually comes from. We basically just need an array of hash references and an iterator class with a next and a count method. For your convenience you can create an iterator from Template::Flute::Iterator class very easily.
DROPDOWNS
Iterators can be used for dropdowns (HTML <select> elements) as well.
Template:
<select class="color"></select>
Specification:
<value name="color" iterator="colors"/>
Code:
@colors = ({value => 'red', label => 'Red'},
{value => 'black', label => 'Black'});
$flute = Template::Flute->new(template => $html,
specification => $spec,
iterators => {colors => \@colors},
values => {color => 'black'},
);
HTML output:
<select class="color">
<option value="red">Red</option>
<option value="black" selected="selected">Black</option>
</select>
Custom iterators for dropdowns
By default, the iterator for a dropdown is an arrayref of hashrefs with two hardcoded keys: value
and (optionally) label
. You can override this behaviour in the specification with iterator_value_key
and iterator_name_key
to use your own hashref's keys from the iterator, instead of value
and label
.
Specification:
<specification>
<value name="color" iterator="colors"
iterator_value_key="code" iterator_name_key="name"/>
</specification>
Template:
<html>
<select class="color">
<option value="example">Example</option>
</select>
</html>
Code:
@colors = ({code => 'red', name => 'Red'},
{code => 'black', name => 'Black'},
);
$flute = Template::Flute->new(template => $html,
specification => $spec,
iterators => {colors => \@colors},
values => { color => 'black' },
);
$out = $flute->process();
Output:
<html>
<head></head>
<body>
<select class="color">
<option value="red">Red</option>
<option selected="selected" value="black">Black</option>
</select>
</body>
</html>
LISTS
Lists can be accessed after parsing the specification and the HTML template through the HTML template object:
$flute->template->lists();
$flute->template->list('cart');
Only lists present in the specification and the HTML template can be addressed in this way.
See Template::Flute::List for details about lists.
FORMS
Forms can be accessed after parsing the specification and the HTML template through the HTML template object:
$flute->template->forms();
$flute->template->form('edit_content');
Only forms present in the specification and the HTML template can be addressed in this way.
See Template::Flute::Form for details about forms.
FILTERS
Filters are used to change the display of value and param elements in the resulting HTML output:
<value name="billing_address" filter="eol"/>
<param name="price" filter="currency"/>
The following filters are included:
- upper
-
Uppercase filter, see Template::Flute::Filter::Upper.
- strip
-
Strips whitespace at the beginning at the end, see Template::Flute::Filter::Strip.
- eol
-
Filter preserving line breaks, see Template::Flute::Filter::Eol.
- nobreak_single
-
Filter replacing missing text with no-break space, see Template::Flute::Filter::NobreakSingle.
- currency
-
Currency filter, see Template::Flute::Filter::Currency. Requires Number::Format module.
- date
-
Date filter, see Template::Flute::Filter::Date. Requires DateTime and DateTime::Format::ISO8601 modules.
- country_name
-
Country name filter, see Template::Flute::Filter::CountryName. Requires Locales module.
- language_name
-
Language name filter, see Template::Flute::Filter::LanguageName. Requires Locales module.
- json_var
-
JSON to Javascript variable filter, see Template::Flute::Filter::JsonVar. Requires JSON module.
Filter classes are loaded at runtime for efficiency and to keep the number of dependencies for Template::Flute as small as possible.
See above for prerequisites needed by the included filter classes.
Chained Filters
Filters can also be chained:
<value name="note" filter="upper eol"/>
Example template:
<div class="note">
This is a note.
</div>
With the following value:
Update now!
Avoid security hazards!
The HTML output would look like:
<div class="note">
UPDATE NOW!<br />
AVOID SECURITY HAZARDS!
</div>
INSERT HTML AND INCLUDE FILES
INSERT HTML
HTML can be generated in the code or retrieved from a database and inserted into the template through the hook
operation:
<value name="description" op="hook"/>
The result replaces the inner HTML of the following div
tag:
<div class="description">
Sample content
</div>
INCLUDE FILES
Files, especially components for web pages can be processed and included through value elements with the include attribute:
<value name="sidebar" include="component.html"/>
The result replaces the inner HTML of the following div
tag:
<div class="sidebar">
Sample content
</div>
AUTHOR
Stefan Hornburg (Racke), <racke@linuxia.de>
BUGS
Please report any bugs or feature requests to bug-template-flute at rt.cpan.org
, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Template-Flute.
SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Template::Flute
You can also look for information at:
RT: CPAN's request tracker
AnnoCPAN: Annotated CPAN documentation
CPAN Ratings
Search CPAN
ACKNOWLEDGEMENTS
Thanks to David Previous (bigpresh) for writing a much clearer introduction for Template::Flute.
Thanks to Grega Pompe for proper implementation of nested lists and a documentation fix.
Thanks to Ton Verhagen for being a big supporter of my projects in all aspects.
Thanks to Sam Batschelet helping me with a bug causing duplicate form fields (GH #14).
Thanks to Terrence Brannon for spotting a documentation mix-up.
HISTORY
Template::Flute was initially named Template::Zoom. I renamed the module because of a request from Matt S. Trout, author of the HTML::Zoom module.
LICENSE AND COPYRIGHT
Copyright 2010-2014 Stefan Hornburg (Racke) <racke@linuxia.de>.
This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License.
See http://dev.perl.org/licenses/ for more information.