Functions

Functions act as filters on their arguments. The arguments are passed to a piece of Perl code, and the template processor replaces the function call with the return value of the executed code.

{% escape_html(header) %}

This would call a function escape_html() and replace the call with whatever the function returned.

This section describes the functions that ship with Imperia and are available inside your view templates. Additional functions may be available, if more modules in the namespace Dynamic::ViewImport have been installed.

Array#

DESCRIPTION#

This module provides typical operations for arrays and references to arrays.

FUNCTIONS#

The module exports the following functions by default:

sort(ARRAY[, FUNCTION, ARGUMENTS, ...])#

Sorts and returns ARRAY. You can pass the name of a function (as a string!) used for sorting, and optionally arguments to pass to that function. Example:

{% files = sort (files, 'by_metafield', 'published') %}

push(ARRAY[, ARGUMENTS, ...])#

Pushes ARGUMENTS onto the list that ARRAY points to. Unlike its Perl equivalent, this function returns an empty string! Example:

{% push (colors, 'red', 'green', 'blue') %}

This should make it also clear, why the function returns an empty string.

shift(ARRAY)#

Removes the first argument from the list that ARRAY points to. Attention! This function returns the empty string. Save the first element before, if you need it.

join(DELIMITER[, ARGUMENTS, ...])#

Concatentes arguments ARGUMENTS separated by DELIMTER. Example:

{% join (' + ', a, b, c) %} = {% a + b + c %}

splice(ARRAY[, OFFSET, LENGTH, LIST])#

Removes the elements designated by OFFSET and LENGTH from an ARRAY, and replaces them with the elements of LIST, if any. This function returns the removed elements from the ARRAY.

Class#

DESCRIPTION#

This module provides class-related helper functions for use in Imperia view templates. All functions described here will automatically load the relevant Perl module that defines the class with the Perl function require().

FUNCTIONS#

The module exports the following functions by default:

new(CLASS[, ARGS])#

Invokes the class method new() for class CLASS. You can optionally pass a list of arguments that will be passed verbatim to the method.

class(CLASS, METHOD [, ARGS])#

Invokes the class method METHOD for class CLASS. You can optionally pass a list of arguments that will be passed verbatim to the method.

can(SOMETHING, METHOD)#

Just a wrapper around UNIVERSAL::can(). SOMETHING can either be a class name or a blessed reference. If it is a blessed refererence, can() will be called as an object method, otherwise as a class method.

isa(SOMETHING, METHOD)#

Just a wrapper around UNIVERSAL::isa(). SOMETHING can either be a class name or a blessed reference. If it is a blessed refererence, isa() will be called as an object method, otherwise as a class method.

VERSION(SOMETHING[, REQUIRE])#

Just a wrapper around UNIVERSAL::VERSION(). SOMETHING can either be a class name or a blessed reference. If it is a blessed refererence, VERSION() will be called as an object method, otherwise as a class method.

require(CLASS)#

Will call require() with CLASS as an argument.

Core#

DESCRIPTION#

This module provides very basic functions.

FUNCTIONS#

The module exports the following functions by default:

exists(VARIABLE, INDEX)#

Returns true if VARIABLE can be indexed by INDEX, false otherwise.

A variable can be indexed by INDEX, iff it is a hash or array reference, and if it has such a hash key or element index respectively.

defined(VARIABLE[, VARIABLE...])#

Returns true if its argument list is defined. Please note that empty argument lists are always undefined, and argument lists of more than one element are always defined (per definitionem). Examples: {% defined() %}

<!--% List of more than one element, always true. -->
{% defined(foo, bar) %}

<!--% True if something.somewhere is defined, false otherwise. -->
{% defined(something.somewhere) %}

delete(WHAT, INDEX)#

If WHAT is a an array or hash reference, deletes the element pointed at by INDEX.

The function always returns the empty string.

call(FUNCTION[, ARGUMENTS...])#

Calls the function previously defined via a #function plug-in. The name of the function must be passed as a string!

Inside of the function you can get the argument array by the special variable "argv" (an array reference).

Functions are visible in the current scope and all child scopes.

Example:

{% #function (footer) %}
    {% company = argv[0];
        year = argv[1];
    %}
    Copyright {% company %}, {% year %}
{% #end %}
{% call('footer', 'Imperia AG', 2010) %}

alphanumerically()#

Compare $a and $b alphanumerically. You can therefore use the string "alphanumerically" as an argument to Dynamic::ViewImport::Array::sort().

numerically()#

Compare $a and $b numerically. You can therefore use the string "numerically" as an argument to Dynamic::ViewImport::Array::sort().

ref REFERENCE#

Returns an empty string if REFERENCE is not a Perl reference. Otherwise the type of reference is returned, exactly like the Perl builtin function ref() would do.

typeof REFERENCE#

Returns the base type of REFERENCE. Returns the empty string if REFERENCE is not a Perl reference. Otherwise it returns one of

SCALAR
ARRAY
HASH
CODE
REF
GLOB
LVALUE

die MESSAGE#

Throws a fatal exception MESSAGE.

filetest_r FILENAME#

Returns true if FILENAME is readable by effective uid/gid, false otherwise.

filetest_w FILENAME#

Returns true if FILENAME is writable by effective uid/gid, false otherwise.

filetest_x FILENAME#

Returns true if FILENAME is executable by effective uid/gid, false otherwise.

filetest_o FILENAME#

Returns true if FILENAME is owned by effective uid/gid, false otherwise.

filetest_R FILENAME#

Returns true if FILENAME is readable by real uid/gid, false otherwise.

filetest_W FILENAME#

Returns true if FILENAME is writable by real uid/gid, false otherwise.

filetest_X FILENAME#

Returns true if FILENAME is executable by real uid/gid, false otherwise.

filetest_O FILENAME#

Returns true if FILENAME is owned by real uid/gid, false otherwise.

filetest_e FILENAME#

Returns true if FILENAME exists, false otherwise.

filetest_z FILENAME#

Returns true if FILENAME has zero size (is empty), false otherwise.

filetest_s FILENAME#

Returns true if FILENAME has non-zero size (returns size in bytes), false otherwise.

filetest_f FILENAME#

Returns true if FILENAME is a plain file, false otherwise.

filetest_d FILENAME#

Returns true if FILENAME is a directory, false otherwise.

filetest_l FILENAME#

Returns true if FILENAME is a symbolic link, false otherwise.

filetest_p FILENAME#

Returns true if FILENAME is a named pipe (FIFO), or file handle is a pipe, false otherwise.

filetest_S FILENAME#

Returns true if FILENAME is a socket, false otherwise.

filetest_b FILENAME#

Returns true if FILENAME is a block special file, false otherwise.

filetest_c FILENAME#

Returns true if FILENAME is a character special file, false otherwise.

filetest_t FILEHANDLE#

Returns true if FILEHANDLE is opened to a tty, false otherwise.

filetest_u FILENAME#

Returns true if FILENAME has setuid bit set, false otherwise.

filetest_g FILENAME#

Returns true if FILENAME has setgid bit set, false otherwise.

filetest_k FILENAME#

Returns true if FILENAME has sticky bit set, false otherwise.

filetest_T FILENAME#

Returns true if FILENAME is an ASCII text file (heuristic guess), false otherwise.

filetest_B FILENAME#

Returns true if FILENAME is a "binary" file (opposite of filetest_T()), false otherwise.

filetest_M FILENAME#

Web server instance start time minus file modification time in days. This function is completely useless and only here for completeness.

filetest_A FILENAME#

Web server instance start time minus file access time in days. This function is completely useless and only here for completeness.

filetest_C FILENAME#

Web server instance start time minus inode change time in days. This function is completely useless and only here for completeness.

HTML#

DESCRIPTION#

This module provides HTML related helper functions for use in Imperia view templates.

FUNCTIONS#

The module exports the following functions by default:

raw(STRING)#

Will echo its argument STRING verbatim to the output. However, the output of raw() is safe in all contexts.

escape_html(STRING)#

A wrapper around Imperia::Util::String::HTML::escape_html(). The output of the function is safe in context "HTML".

escape_xml(STRING)#

A wrapper around Imperia::Util::String::XML::escape_xml(). The output of the function is safe in context "HTML".

escape_js(STRING)#

A wrapper around Imperia::Util::String::HTML::escape_js(). The output of the function is safe in contexts "JAVASCRIPT" and "HTML".

escape_form_value(STRING)#

A wrapper around Imperia::Util::String::URI::escape_form_value(). The output of the function is safe in context "JAVASCRIPT" and "HTML".

uri_encode(STRING)#

A wrapper around IWL::String::encodeURIComponent(). The output of the function is safe in context "HTML".

uri_highlight(STRING)#

Converts everything in STRING that looks like a URI into a link. See URI::Find::Schemeless(3pm) for details.

br(STRING[, TRIM])#

Converts all newlines in STRING into HTML br elements.

If the optional argument TRIM is true, then all whitespace will be removed from STRING before the substitution is applied.

select(NAME, OPTIONS[, SELECTED])#

A simple way to produce an HTML select element. The meaning of the arguments is best explained with an example:

{% select('color',
    [ 'r', 'red', 'g', 'green', 'b', 'blue' ], 'g') %}

Or an alternative writing using the fat comma:

{% select(color =>
    [ r => 'red', g => 'green', b => 'blue' ], 'g') %}

The function will produce the following html from that:

<select name="color">
    <option value="r">red</option>
    <option value="g" selected="selected">green</option>
    <option value="b">blue</option>
</select>

If you omit the optional third argument SELECTED, the first option encountered will be the selected one, unless a select with the multiple attribute is created.

If you are defining a multiple select box, the last argument, selected, can also be an array ref:

{% select({ name => 'color', size => 3, multiple => 'multi-
ple', }, [ r => 'red', g => 'green', b => 'blue' ], ['g',
'b']) %}

Would result in the following select box:

<select name="color" multiple='multiple' size="3">
<option value="r">red</option>
<option value="g" selected="selected">green</option>
<option value="b" selected="selected">blue</option>
</select>

You can use a hash reference as the first argument, if you happen to need more attributes:

{% select({ name => 'color', id => 'color_select', class => 'sc' },
[ r => 'red', g => 'green', b => 'blue' ], 'g') %}

If the value of an option is an array reference, it is interpreted as an optgroup element.

{% select(color => [
        'RGB colors', [
            r => 'red',
            g => 'green',
            b => 'blue',
        ],
        'Mixed colors', [
            c => 'cyan',
            m => 'magenta',
            y => 'yellow',
        ],
    ]) %}

This would produce:

<select name="color">
    <optgroup label="RGB colors">
        <option value="r" selected="selected">red</option>
        <option value="g">green</option>
        <option value="b">blue</option>
    </optgroup>
    <optgroup label="Mixed colors">
        <option value="c">cyan</option>
        <option value="m">magenta</option>
        <option value="y">yellow</option>
        </optgroup>
</select>

It is currently not possible to set any other attribute of the optgroup element.

Finally, if the value of an option is a hash reference, you can also set attributes of individual options:

{% select(color => [ c => 'cyan', m => 'magenta', y => 'blue',
    k => { id => 'black_id', text => 'black' },
    ]) %}

This would produce:

<select name="color">
    <option value="c" selected="selected">cyan</option>
    <option value="m">magenta</option>
    <option value="y">yellow</option>
    <option value="k" id="black_id">black</option>
</select>

You may have noticed that the illegal attribute name "text" is interpreted as the content of the option.

All values used in attributes are automatically run through uri_encode().

The content of all option elements will not be escaped!

The function is safe in context "HTML".import_css (URI)

import_css (URI)#

Remembers to import CSS as a stylesheet. The URIs are stored in the array reference imperia.import.css, and inserted at the correct place in the head.

The Imperia view templates are designed in a way that you can use this function inside of the document body because the html head gets generated after the body.

insert_css (CSS)#

Just like import_css() but for CSS source code. The default Imperia view templates expand inserts after imports. The CSS code is not escaped! The list of code snippets is stored in imperia.insert.css.

import_js (URI)#

Remembers to import URI as a javascript file. The URIs are stored in the array reference imperia.import.js, and spit out the corresponding script tags at the end of the page body.

insert_js (JS)#

Just like import_js() but for javascript source code. The default Imperia view templates expand inserts after imports. The javascript code is not escaped! The list of code snippets is stored in imperia.insert.js.

import_js_init (URI)#

Just like import_js() but the default Imperia view templates spit the corresponding code out after the regular javascript imports and inits.

The list of URIs is stored in imperia.import.js_init.

insert_js_init (JS)#

Just like import_js_init() but for javascript source code. The default Imperia view templates spit this code out after the corresponding imports.

The list of code snippets is stored in imperia.insert.js_init.

cachable (URI)#

Checks whether URI exists in the web servers document root, and appends a question mark followed by a timestamp for the file's last modification. This will effectively prevent delivery from the client (or proxy) cache if the file has been modified.

If the file cannot be found, the URI is returned unmodified.

Do not use this function as the argument to import_js(), import_js_init(), or import_css(), at least not, when using the standard Imperia view templates. These view templates already call cachable() for all of its arguments.

toJSON(object)#

A wrapper around IWL::JSON::toJSON(). Returns a JSON object from a given Perl object. The output of the function is safe in contexts "JAVASCRIPT" and "HTML".

template_js(string)#

Escapes and wraps the string around Prototype's Template class. The output of this function is safe in contexts "JAVASCRIPT" and "HTML".

ellipsis(label, classname [, options])#

Implements shortening of strings via ellipsis. The label is the label that the user wants to be shortened. The classname is required for the client-side code to find the element. The options is a hash, with the following recognized keys:

  • position: Specifies the position of the ellipsis. Can be either left, right or center (default).

  • length: The length (in characters) for the shortened string (default: 30).

  • placeTitle: A boolean value, indicating whether to put the full, uncut string, inside a title attribute (default: true).

  • titleElement: If placeTitle is true, place the full string into the title attribute of the element, whose ID is specified here.

  • titleAncestor: If placeTitle is true, place the full string into the title attribute of the Nth ancestor of the element.

Registering the processing of ellipsis on the client-side is done using the following javascript code:

I.Util.ellipsis('classname');

or

I.Util.ellipsisSelector('CSS Selector');

One registration code is required for a group of ellipsis elements, defined by either their class names, or a CSS selector.

Returns an HTML span element, with the options and label to be shortened

REMARKS#

JavaScript and CSS#

You can inject javascript and css from various places in the Imperia system. The system is fragile as it is based on convention only and not enforced by the view processor itself.

See the following scheme for illustration:

<html>
    <head>
    ...
(1) CSS imported by controllers (Perl code)
(2) CSS inserted by controllers (Perl code)
    </head>
    <body>
    ...
(3) CSS imported or inserted from view templates
(included immediately)
...
(4) JavaScript imported by views or controllers
(5) JavaScript inserted by views or controllers
(6) JavaScript init code imported by views or controllers
(7) JavaScript init code inserted by views or controllers
    </body>

The Imperia default template system uses the above scheme for CSS and JavaScript:

CSS references created by the Perl code in the controllers (1 and 2) is inserted via link elements in the head. This is considered bad style since CSS is part of the presentation not the business logic.

Calls to import_css() or insert_css() in view templates (3) are expanded right away. The only advantage over coding <style> elements is that your inserted code or references are protected against multiple inclusion.

All JavaScript references are collected and are resolved right before the closing body tag, no matter whether they were created from within controller code in Perl or in view templates by import_js(), insert_js(), import_js_init(), and insert_js_init(). Directives for normal code is expanded before the initialization code. Imports are expanded before inserts.

The system will never generate the same piece of HTML twice for these directives. That means that it will never include the same external file twice, or insert the same code (JavaScript or CSS) twice.

I18N#

DESCRIPTION#

This module provides the interface to Locale::TextDomain(3pm) from Imperia view templates.

FUNCTIONS#

The module exports the following functions by default:

__(STRING)#

A wrapper around Locale::TextDomain::__().

N__(STRING)#

Does nothing, just marks STRING for translation.

__X(STRING[, KEY => VALUE, KEY => VALUE])#

A wrapper around Imperia::Util::String::HTML::__x().

Imperia#

DESCRIPTION#

This module provides functions specific to the use in Imperia.

FUNCTIONS#

The module exports the following functions by default:

uri(ACTION[, ...])#

Constructs an absolute URI based on ACTION. If ACTION is omitted, the current controller URI is assumed.

For your convenience you can add more strings that are simply concatenated with the resulting string.

Example: {% uri('/document/publisher/queue', '/publish', '/123') %}

Would result in something like:

https://imperia.pany.com/imp/document/publisher/queue/publish/123

Regex#

DESCRIPTION#

This module gives you full access to Perl regular expressions in your view templates.

One potential problem, when using this module, are escaping issues, if you have a background in Perl or JavaScript. In Perl you can write the following:

if ($string =~ /index\.html/) {
    do_something($string);
}

This will match the variable $string against the regular expression pattern "index.html". A regular expression is essentially a string. But the Perl Interpreter (and JavaScript, and ... you name it) have built-in support for regular expressions that the Imperia View processor does not have (of course).

The first consequence is that you cannot use the slash for delimiting regular expressions.

The second consequence is more important: The backslash has its own semantics in regular expressions. But since the input to the regex functions defined here are ordinary strings, you have to escape backslashes so that the regular expression engine will see them. That basically boils down to: You have to double backslashes. The above example would code in view template like this:

if (match (string, "index\\.html")) {
    do_something($string);
}

If you want to find out whether a string contains a backslash, you have to test like this:

if (match (string, "\\\\")) {
    result = "has backslash";
}

If you have used regular expressions in programming languages like C or Java this will be familiar to you.

FUNCTIONS#

The module exports the following functions by default:

match(STRING, PATTERN[, MODIFIERS[, CAPTURE[, NUM_CAPTURES]]])#

Matches STRING against PATTERN and returns true if the string matches, false otherwise.

If you capture submatches, you should provide an array reference CAPTURE that will be filled with the captured substrings. The maximum number of strings captured will be 9 or NUM_CAPTURES if given. The array will be emptied first. You can therefore use it for testing if the match succeded.

MODIFIERS should be a string consisting of one or more of the following letters:

  • i: Do case-insensitive pattern matching.

  • m: Treat string as multiple lines. That is, change "^" and "$" from matching the start or end of the string to matching the start or end of any line anywhere within the string.

  • s: Treat string as single line. That is, change "." to match any character whatsoever, even a newline, which normally it would not match.

  • u: Treat both PATTERN and STRING as UTF-8 encoded strings, and match using character semantics, not byte semantics. This will slow down the matching, only use it, when you need it.

replace(STRING, PATTERN, REPLACE[, MODIFIERS[, CAPTURE[, NUM_CAPTURES]]])#

Searches STRING for PATTERN and - if found - replaces PATTERN with REPLACEMENT.

The function always returns the modified STRING. That means you cannot use it for testing for a match! If you have to know whether the match succeded you can either compare the original string with the result or capture submatches.

If you capture submatches, you should provide an array reference CAPTURE that will be filled with the captured substrings. The maximum number of strings captured will be 9 or NUM_CAPTURES if given. The array will be emptied first. You can therefore use it for testing if the match succeded.

MODIFIERS should be a string consisting of one or more of the following letters:

  • g: Do a global substitution, i. e. do not replace only the first match but all of them.
  • i: Do case-insensitive pattern matching.
  • m: Treat string as multiple lines. That is, change "^" and "$" from matching the start or end of the string to matching the start or end of any line anywhere within the string.
  • s: Treat string as single line. That is, change "." to match any character whatsoever, even
  • a newline, which normally it would not match.
  • u: Treat both PATTERN and STRING as UTF-8 encoded strings, and match using character semantics, not byte semantics. This will slow down the matching, only use it, when you need it.

SiteActive#

DESCRIPTION#

This module provides helper functions for site active views. They provide maximum compatibility to the old Site Active syntax. However, they pollute the namespace with functions of limited usefulness. Expect another module with similar functionality but clearer interface to be written soon as an alternative to this module.

FUNCTIONS#

The module exports the following functions by default:

ireaddir([DIRECTORY ...])#

The function searches recursively for documents managed by Imperia in directory DIRECTORY (you can pass multiple directories). It returns a reference to a list of Meta::Info::Hashed(3pm) objects. The method cannot fail.

The results are not sorted in any particular order.

If called without an argument, the function searches the document root.

This function can be used as a replacemen for the old site active "READDIR" syntax.

fireaddir([DIRECTORY])#

(think: flat ireaddir). Like ireaddir() but does not recurse into subdirectories.

This function can be used as a replacemen for the old site active "READDIR" syntax.

by_uri A, B#

Can be used as an argument to the function sort() in Dynamic::ViewImport::Array(3pm). Sorts alphanumerically by path and filename.

The function expects A and B to be two Meta::Info(3pm) objects, and returns the result of the Perl cmp operator when applied to the return value of the method getURI() of A and B. Example:

{%
    entries = readdir ('/news/sports');
    entries = sort (entries, 'by_uri');
%}

This function can be used as a replacement for the old site active "SORT BY FILENAME" syntax.

latest_first A, B#

Can be used as an argument to the function sort() in Dynamic::ViewImport::Array(3pm). Sorts by the time the corresponding file was last modified. More recent entries appear first in the result.

The function expects A and B to be two Meta::Info(3pm) objects, and returns the result of the Perl cmp operator when applied to the return value of the method getURI() of A and B. Example:

{%
    entries = readdir ('/news/sports');
    entries = sort (entries, 'latest_first');
%}

For compatibility reasons this functions uses the timestamp of the corresponding file under 'site/meta' when sorting. This is both slow and unreliable. Consider sorting by a meta field instead (see below by_metafield()).

This function can be used as a replacement for the old site active "SORT LATEST FIRST" syntax.

oldest_first A, B#

Can be used as an argument to the function sort() in Dynamic::ViewImport::Array(3pm). Sorts by the time the corresponding file was last modified. Older entries appear first in the result.

The function expects A and B to be two Meta::Info(3pm) objects, and returns the result of the Perl cmp operator when applied to the return value of the method getURI() of A and B. Example:

{%
    entries = readdir ('/news/sports');
    entries = sort (entries, 'oldest_first');
%}

For compatibility reasons this functions uses the timestamp of the corresponding file under 'site/meta' when sorting. This is both slow and unreliable. Consider sorting by a meta field instead (see below by_metafield()).

This function can be used as a replacement for the old site active "SORT OLDEST FIRST" syntax.

filemask ARRAY, REGEX#

Applies REGEX to the URI of all members of ARRAY, and returns a new array reference with all matching entries.

ARRAY must be a reference to an array of Meta::Info(3pm) objects.

REGEX must be a valid Perl regular expression. If you use a literal string, remember that X uses the backslash for its own purposes. If you want to escape regular expression meta characters, you will usually have to doubly escape the backslash:

{% entries = filemask(entries, '^index\\.html$') %}

But, if you would want to match against entries with an apostrope in the filename, you have to:

{% entries = filemask(entries, '\'') %}

This function can be used as a replacement for the old site active "FILEMASK" syntax.

limit ARRAY, COUNT#

Returns the first COUNT element of ARRAY.

ARRAY must be an array reference. The return value is a new array reference with the first COUNT members of the ARRAY. If ARRAY has less than COUNT members, only that many members are returned.

Example:

{% entries = limit (entries, 10) %}

This function can be used as a replacemen for the old site active "LIMIT" syntax.

String#

DESCRIPTION#

This module provides typical string operations in Imperia view templates.

FUNCTIONS#

The module exports the following functions by default:

concat(STRING[, ...])#

This function concatenates its arguments.

gen_id([LENGTH])#

Generate a random ID string. The id string will be made of hex characters ([0-9a-f ]) and be of length LENGTH. LENGTH defaults to 20.

substr(ARGUMENTS)#

Works exactly like the Perl function substr().

length(STRING)#

Returns the number of characters (letters/symbols) in the given string.

chars(STRING)#

Split STRING into an array of characters. Use this function for textual data only.

bytes(STRING)#

Split STRING into a reference to an array of bytes. Use this function for binary data only.

ord(CHAR)#

Return the code number of CHAR (a character or byte).

uc(STRING)#

Return the upper-cased string.

split(DELIMITER, STRING)#

Splits the given string with the given delimiter.

empty(STRING)#

Returns true if the string is empty (contains only white-spaces)

BUGS#

The function gen_id() has a weakness which is an illustration of the so-called birthday paradoxon. If you use it for id attributes, it is not very probable that another id attribute has the same value. However, for a length of 20, if you generate about 1.3E12 (13 plus 11 zeros) IDs, the odds are already about 50 percent that two IDs will collide.

Util#

DESCRIPTION#

This module provides typical utility functions in Imperia view templates.

FUNCTIONS#

The module exports the following functions by default:

dump(VARIABLE[, ...])#

Dumps its arguments like Dumper() in Data::Dumper(3pm) does.

warn(VARIABLE[, ...])#

The same functionality as dump, but the output is written to STDERR.