Swark¶
Authors: | Jan Kudlicka, Seeds Consulting AS, http://www.seeds.no/ Aplia AS, https://www.aplia.no |
---|
Table of Contents
The Swark extension implements a set of highly needed template operators and workflow event types which are sorely missing from eZ publish legacy.
Operators¶
add_view_parameters¶
Summary¶
Returns the input path extended by the view parameters.
Usage¶
input|add_view_parameters( view_parameters )
Parameters¶
Name Description Required Default view_parameters View parameters to add to the input path Yes
Examples¶
{$node.url|add_view_parameters( $view_parameters )|ezurl}
In a node’s full view template reconstructs the request URL. See also the modify_view_parameter operator.
array_search¶
Summary¶
Searches the input array for a given value and returns the corresponding key.
Usage¶
input|array_search( search [, not_found_key] )
Parameters¶
Name Description Required Default search Searched value Yes not_found_key Value to return in the case the searched value is not found No -1
Examples¶
{array( 'apple', 'pear', 'pineapple', 'orange' )|array_search( 'pear' )}
Returns 1.
{array( 'apple', 'pear', 'pineapple', 'orange' )|array_search( 'carrot' )}
Returns -1.
{array( 'apple', 'pear', 'pineapple', 'orange' )|array_search( 'carrot', 'not_found' )}
Returns ‘not_found’.
{hash( 'apple', 'red',
'pear', 'green',
'pineapple', 'yellow',
'orange', 'orange' )|array_search( 'yellow' )}
Returns ‘pineapple’.
arsort¶
Summary¶
Sorts and returns the input array in reverse order, maintaining index associations.
Usage¶
input|arsort
Parameters¶
None.
Examples¶
{hash( 'a', 10, 'c', 2, 'd', 15, 'b', 8, 'e', 6 )|arsort}
Returns array( ‘d’ => 15, ‘a’ => 10, ‘b’ => 8, ‘e’ => 6, ‘c’ => 2 ).
asort¶
Summary¶
Sorts and returns the input array, maintaining index associations.
Usage¶
input|asort
Parameters¶
None.
Examples¶
{hash( 'a', 10, 'c', 2, 'd', 15, 'b', 8, 'e', 6 )|asort}
Returns array( ‘c’ => 2, ‘e’ => 6, ‘b’ => 8, ‘a’ => 10, ‘d’ => 15 ).
clear_object_cache¶
Summary¶
Clears the content objects memory cache.
Usage¶
clear_object_cache()
Parameters¶
None.
Examples¶
{clear_object_cache()}
Using this operator might be useful when processing huge number of content objects. Instead of fetching all objects at once and risking to exhaust all available memory, use a cycle to fetch a small slice of objects and to process them. Clear the memory cache using the operator before continuing with a next iteration.
cookie¶
Summary¶
Returns the value of the HTTP cookie identified by the parameter.
Usage¶
cookie( name )
Parameters¶
Name Description Required Default name The name of the cookie Yes
current_layout¶
Summary¶
Returns the name of the current layout (set by, for example, the layout/set function) or false for the standard layout.
Usage¶
current_layout()
debug_attributes¶
Summary¶
Shows attribute values in the debug output. This operator is equivalent to “attribute( show )” but uses the debug output.
Usage¶
input|debug_attributes( [header] [, depth] )
Parameters¶
Name Description Required Default header Header/title of a debug notice No Debug attributes operator depth Number of levels to show No 2
For convenience, the order of parameters can be interchanged.
Examples¶
{$node|debug_attributes}
Shows attribute values of $node.
{$node|debug_attributes( 'Dump of $node' )}
Shows attribute values of $node as a notice titled ‘Dump of $node’.
{$node|debug_attributes( 'Dump of $node', 1 )}
or:
{$node|debug_attributes( 1, 'Dump of $node' )}
Shows attributes values of $node (but not attributes of object attributes) as a notice titled ‘Dump of $node’.
debug¶
Summary¶
Adds a notice to the debug output.
Usage¶
input|debug( [ header ] )
Parameters¶
Name Description Required Default header Header/title of a notice No Debug operator
Examples¶
{concat( 'Node ID =', $node.node_id )|debug}
Adds a notice about the node ID of $node to the debug output.
{$variable|debug( 'Content of $variable' )}
Dumps $variable to the debug output as a notice titled ‘Content of $variable’. See also the debug_attributes operator.
dump¶
Summary¶
Dumps content of variable or expression using Symfony dump() function.
Usage¶
input|dump( [ value ] )
Parameters¶
Name Description Required Default value The value to dump if input is not set No
Examples¶
{$node|dump}
Displays the content of the $node variable.
{dump($node)}
Same as above but variable passed as parameter.
is_post_request¶
Summary¶
Returns true if the current request method is POST, false otherwise.
Usage¶
is_post_request()
Parameters¶
None.
Examples¶
This is a {if is_post_request()}POST{else}GET{/if} request.
Shows ‘This is a POST request’ if the current request is POST, ‘This is a GET request’ otherwise.
json_encode¶
Summary¶
Returns the JSON representation of input.
Usage¶
input|json_encode
json_encode(input)
Parameters¶
None.
Examples¶
{json_encode( 3.1415 )}
Returns [“3.1415”].
{json_encode( array( hash( 'a', 1, 'b', 2 ), 'Test', false(), 1.2345 ) )}
Returns [{“a”:1,”b”:2},”Test”,false,”1.234500”].
krsort¶
Summary¶
Sorts and returns the input array by key in reverse order.
Usage¶
input|krsort
Parameters¶
None.
Examples¶
{hash( 'a', 10, 'c', 2, 'd', 15, 'b', 8, 'e', 6 )|krsort}
Returns array( ‘e’ => 6, ‘d’ => 15, ‘c’ => 2, ‘b’ => 8, ‘a’ => 10 ).
ksort¶
Summary¶
Sorts and returns the input array by key.
Usage¶
input|ksort
Parameters¶
None.
Examples¶
{hash( 'a', 10, 'c', 2, 'd', 15, 'b', 8, 'e', 6 )|ksort}
Returns array( ‘a’ => 10, ‘b’ => 8, ‘c’ => 2, ‘d’ => 15, ‘e’ => 6 ).
ltrim¶
Summary¶
Strips whitespaces (or characters in the parameter, if given) from the beginning of the input string.
Usage¶
input|ltrim( [ charlist] )
Parameters¶
Name Description Required Default charlist String containing characters to be removed No
Examples¶
{' -- Hello, world! -- '|ltrim}
Returns ‘– Hello, world! – ‘.
{' -- Hello, world! -- '|ltrim( ' -' )}
Returns ‘Hello, world! – ‘.
modify_view_parameter¶
Summary¶
Adds, removes or changes a view (user) parameter in the input path.
Usage¶
input|modify_view_parameter( parameter, value )
Parameters¶
Name Description Required Default parameter Name of view (user) parameter to add, remove or change Yes value New value or false to remove the parameter Yes
Examples¶
{'/path/to/node/(sort)/name/(offset)/10'|modify_view_parameter( 'sort', 'modified' )}
Returns ‘/path/to/node/(sort)/modified/(offset)/10’.
{'/path/to/node/(sort)/name/(offset)/10'|modify_view_parameter( 'sort', false() )}
Returns ‘/path/to/node/(offset)/10’.
{'/path/to/node/(sort)/name/(offset)/10'|modify_view_parameter( 'sort_order', 'desc' )}
Returns ‘/path/to/node/(sort)/name/(offset)/10/(sort_order)/desc’.
preg_match¶
Summary¶
Returns number of matches of a given (Perl-style) regular expression in the input string.
Usage¶
input|preg_match( pattern )
Parameters¶
Name Description Required Default pattern Regular expression to search for Yes
preg_replace¶
Summary¶
Performs a regular expression search and replace.
Usage¶
input|preg_replace( search, replace )
Parameters¶
Name Description Required search The pattern (Perl-compatible regular expression) to search for (or array of such patterns) Yes replace Replacement string (or array of such strings) Yes
For more information see http://php.net/preg_replace.
Examples¶
{'Hello, John and Peter!'|preg_replace( array( '/John/', '/Peter/' ), array( 'Jane', 'Petra' ) )}
returns ‘Hello, Jane and Petra!’.
{'John Doe'|preg_replace( '/(\w+) (\w+)/', '$2, $1' )}
returns ‘Doe, John’.
range¶
Summary¶
Returns an array of integers within the given range.
Usage¶
range( min, max [, step] )
Parameters¶
Name Description Required Default min The minimum value, inclusive Yes max The maximum value, inclusive Yes step Increment between elements No 1
Note: min and max might be interchanged. The sign of step is not important.
Examples¶
{range( 1, 10 )}
Returns array of integers from 1 to 10 inclusive.
{range( 1, 12, 3 )}
Returns array( 1, 4, 7, 10 ).
{range( 5, 2 )}
Returns array( 5, 4, 3, 2 ).
{range( 9, 2, 2 )}
or:
{range( 9, 2, -2 )}
Returns array( 9, 7, 5, 3 ).
redirect¶
Summary¶
Stops execution and redirects to the given URL. The URL can be specified as a relative path in which the siteaccess and path-prefix is prefixed, or as an absolute URL. In addition the url format can be tweaked using parameter type. Redirection is done using the HTTP status code 302 (temporary redirect) by default but can be changed using parameter status.
Parameters¶
Name Description Required Default url Address to redirect to Yes status HTTP status code No 302 type Control generated url No
Examples¶
{redirect( 'book/article' )}
Stops execution and redirects to the relative path. The current eZ publish siteaccess or other path-prefix is prefixed to the path. e.g. if there is no prefix or siteaccess it redirects to /book/article, alternatively if the siteaccess is /en it redirects to /en/book/article.
{'http://www.seeds.no'|redirect}
Stops execution and redirects to absolute URL http://www.seeds.no.
{redirect( $node.parent.url, 301 )}
Stops execution and redirects to the parent node of $node, returning status code 301 (permanent redirection).
{redirect( $node.parent.url, , 'abs')}
Stops execution and redirects to the parent node but force using an absolute url. This will detect http vs https, even behind a proxy, and add the proper scheme in front of the host.
{redirect( '/about', , 'root')}
Stops execution and redirects using a relative url but without prefixing the eZ publish siteaccess to the path. e.g. if the current siteaccess is ‘/en’ the resulting url will be /about.
{redirect( '/about', , 'absroot')}
A combination of type root and abs, ie. it creates an absolute url from the relative url but without prefixing the path element with the current siteaccess. If the siteaccess is /en and the url for the current page is https://example.org/en/content/view then the resulting url is https://example.org/about.
{redirect( '//example.org' )}
Redirects to another host and path but using the same scheme as the current site. e.g. if the current url is https://somwhere.example.org/about will redirect to https://example.org
remove_array_element¶
Summary¶
Removes an array element in the input array and returns modified array.
Usage¶
input|remove_array_element( key )
Parameters¶
Name Description Required Default key Key of the array element to remove Yes
Examples¶
{hash( 'a', 10, 'c', 2, 'd', 15, 'b', 8, 'e', 6 )|remove_array_element( 'c' )}
Returns array( ‘a’ => 10, ‘d’ => 15, ‘b’ => 8, ‘e’ => 6 ).
return¶
Summary¶
Terminates execution returning input as the response.
Usage¶
input|return( [ content_type ] )
Parameters¶
Name Description Required Default content_type Content type of HTTP response No
Examples¶
{$variable|json_encode|return( 'application/json' )}
Returns value of $variable as JSON document suitable for processing by Javascript.
rsort¶
Summary¶
Sorts and returns the input array in reverse order.
Parameters¶
None.
Examples¶
{hash( 'a', 10, 'c', 2, 'd', 15, 'b', 8, 'e', 6 )|rsort}
Returns array( 15, 10, 8, 6, 2 ).
rtrim¶
Summary¶
Strips whitespaces (or characters in the parameter, if given) from the end of the input string.
Usage¶
input|rtrim( [ charlist] )
Parameters¶
Name Description Required Default charlist String containing characters to be removed No
Examples¶
{' -- Hello, world! -- '|rtrim}
Returns ‘ – Hello, world! –’.
{' -- Hello, world! -- '|rtrim( ' -' )}
Returns ‘ – Hello, world!’.
serialize¶
Summary¶
Returns a storable representation of the input using PHP function serialize().
Usage¶
input|serialize
Parameters¶
None.
Examples¶
Using serialize and unserialize for caching value of variables:
{def $children=false()}
{set-block variable=$children_ser}
{cache-block expiry="0" subtree_expiry="content/view/full/2"}
{set $children=fetch( 'content', 'list', hash( 'parent_node_id', 2, 'as_object', false() ) )}
{$children|serialize}
{/cache-block}
{/set-block}
{if $children|not}
{set $children=$children_ser|trim|unserialize}
{/if}
server¶
Summary¶
Returns content of the server variable identified by the parameter. By server variables we understand information such as headers, paths, and script locations, variables defined in CGI specification etc. For more information, see http://php.net/reserved.variables.server
Usage¶
server( variable_name )
Note: Variable name is case insensitive, the operator will capitalize it before obtaining its value.
Parameters¶
Name Description Required Default variable_name Name of the server variable to return Yes
Examples¶
{server( 'remote_addr' )}
Returns the client’s IP address.
{server( 'http_referer' )}
Returns from which URL the client got to the current page.
{server( 'http_user_agent' )}
Returns the identification of client’s browser.
set_array_element¶
Summary¶
Sets an array element in the input array and returns the modified array.
Usage¶
input|set_array_element( key, value )
Parameters¶
Name Description Required Default key Key of the array element to set Yes value Value to assign Yes
Examples¶
{hash( 'a', 10, 'c', 2, 'd', 15, 'b', 8, 'e', 6 )|set_array_element( 'c', 0 )}
Returns array( ‘a’ => 10, ‘c’ => 0, ‘d’ => 15, ‘b’ => 8, ‘e’ => 6 ).
{hash( 'a', 10, 'c', 2, 'd', 15, 'b', 8, 'e', 6 )|set_array_element( 'f', 12 )}
Returns array( ‘a’ => 10, ‘c’ => 2, ‘d’ => 15, ‘b’ => 8, ‘e’ => 6, ‘f’ => 12 ).
shortenw¶
Summary¶
Returns a shortened version of the input string (without breaking words).
Note that ‘w’ at the end of the operator name stands for word.
Usage¶
input|shortenw( length [, ellipsis] )
Parameters¶
Name Description Required Default length Maximum length of the returned string (including ellipsis) Yes ellipsis Ellipsis No …
Examples¶
{'The quick brown fox jumps over the lazy dog'|shortenw( 16 )}
Returns ‘The quick…’.
{'The quick brown fox jumps over the lazy dog'|shortenw( 16, '-' )}
Returns ‘The quick brown-‘.
{'Textwithnospaces'|shortenw( 10 )}
Returns ‘Textwit…’.
shuffle¶
Summary¶
Randomizes the order of the elements in the input array and returns is as output.
Usage¶
input|shuffle
Parameters¶
None
Examples¶
{range( 1, 10 )|shuffle}
Creates an array of numbers from 1 to 10, inclusive, and shuffles them. Note that range is also an operator in the Swark extension.
split_by_length¶
Summary¶
Converts the input string to an array.
Usage¶
input|split_by_length( [ length ] )
Parameters¶
Name Description Required Default length Chunk length or lengths (if array) No 1
Examples¶
{'abcdef'|split_by_length}
Returns array( ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ ).
{'abcdef'|split_by_length( 2 )}
Returns array( ‘ab’, ‘cd’, ‘ef’ ).
{'abcdef'|split_by_length( array( 1, 2, 3 ) )}
Returns array( ‘a’, ‘bc’, ‘def’ ).
{'abcdefgh'|split_by_length( array( 1, 2 ) )}
Returns array( ‘a’, ‘bc’, ‘d’, ‘ef’, ‘g’, ‘h’ ).
strpos¶
Summary¶
Returns position of the first occurrence of the parameter in the input string.
Usage¶
input|strpos( needle [, offset] )
Parameters¶
Name Description Required Default needle Searched string Yes offset Allows to specify at which character in the input to start the search No 0
Examples¶
{'The quick brown fox jumps over the lazy dog'|strpos( 'brown' )}
Returns 10.
{'Does the quick brown fox jumps over the lazy dog?'|strpos( 'the', 6 )}
Returns 36.
str_replace¶
Summary¶
Replaces all occurrences of the search string with the replacement string.
Usage¶
input|str_replace( search, replace )
Parameters¶
Name Description Required search The string to search for (or array of such strings) Yes replace Replacement string (or array of such strings) Yes
strrpos¶
Summary¶
Returns position of the last occurrence of the parameter in the input string.
Usage¶
input|strrpos( needle [, offset] )
Parameters¶
Name Description Required Default needle Searched string Yes
substr¶
Summary¶
Returns part of the input string.
Usage¶
input|substr( start [, length] )
Parameters¶
Name Description Required Default start Position in the input where to start the extraction. If negative, the position will be counted from the end of the input string. Yes length Number of characters to extract, if 0 or not specified, the rest of the string is returned. If negative, it is the number of characters that will be omitted from the end of the input string. No 0
Examples¶
{'The quick brown fox jumps over the lazy dog'|substr( 4 )}
Returns ‘quick brown fox jumps over the lazy dog’.
{'The quick brown fox jumps over the lazy dog'|substr( 4, 11 )}
Returns ‘quick brown’.
{'The quick brown fox jumps over the lazy dog'|substr( 4, -3 )}
Returns ‘quick brown fox jumps over the lazy’.
{'The quick brown fox jumps over the lazy dog'|substr( -8 )}
Returns ‘lazy dog’.
{'The quick brown fox jumps over the lazy dog'|substr( -8, 4 )}
Returns ‘lazy’.
unserialize¶
Summary¶
Returns the value previously stored by the serialize operator.
Usage¶
input|unserialize
Parameters¶
None.
uri_path_segment¶
Summary¶
Returns a segment of the input URL’s path.
Usage¶
input|uri_path_segment( [ index ] )
Parameters¶
Name Description Required Default index Which path segement to return, if negative, counted from the end No -1
Examples¶
{'http://www.seeds.no/nor/content/search?SearchText=publish#results'|uri_path_segment}
Returns ‘search’.
{$child.url|uri_path_segment}
Returns last path segment of $child’s url which can be used as an anchor.
user_id_by_login¶
Summary¶
Returns the user ID of a user identified by the login name.
Usage¶
user_id_by_login( login )
Parameters¶
Name Description Required Default login Login name of a user Yes
variable_names¶
Summary¶
Shows or returns comma separated names of all available template variables. If the parameter is true or 1 or not given, the string is not returned but shown in the debug output.
Usage¶
variable_names( [in_debug] )
Parameters¶
Name Description Required Default in_debug If true, uses debug output instead of returning the names No 1
Examples¶
{variable_names()}
Placed in the pagelayout.tpl, it adds a debug notice ‘$module_result, $site, $ezinfo, $current_user, $anonymous_user_id, $access_type, $warning_list, $navigation_part, $uri_string, $requested_uri_string, $ui_context, $ui_component, $DesignKeys:used, $DesignKeys:matched’.
embed_design_file¶
Summary¶
Embeds a file from the design folders. Embeds a file located in any design folders on the site. This is similar to the ezdesign operator but will return the contents of the file instead of the path.
This can for instance be used to embed javascript code from a file. The javascript file can then be separate from the template code and can be opened like a normal javascript file in an editor. Another typical use case is to embed handlebar templates or inline CSS.
Usage¶
embed_design_file( <file path> )
Parameters¶
Name Description Required Default file path Path to design file relative from design folder Yes
Examples¶
Pass the relative file path to the operator, for instance javascript/code.js could then be resolved to extension/site/design/site/javscript.code.js if the folder extension/site/design/site contains this file:
{embed_design_file('javascript/code.js')}
If the second parameter is used and set to true then the returned value will contain an HTML element around the file contents if the file type is known, currently only Javascript and CSS files are supported:
{embed_design_file('javascript/code.js', true())}
ezselection_content¶
Summary¶
Alternative for getting object attribute content from ezselection attribute. The default content always returns an array of values, which only contains id’s, whereas this operator returns an array of [<id> => <name>].
In the case of single select, returns the name directly. Bypass this to return id-name-array with the named parameter with_id_as_key to true. This parameter is irrelevant for multiselects.
Usage¶
field|ezselection_content([true])
Parameters¶
Name | Description | Required | Default |
---|---|---|---|
field | eZSelection field from data_map. Do note that we do not pass in the content, and instead the entire field. | Yes | |
with_id_as_key | Whether to include the id of the selection as key. This is implicit for multiselect. | No |
Examples¶
{$data_map.my_ezselection_single_field|ezselection_content}
Returns name string for selected value: ‘<name>’.
{$data_map.my_ezselection_single_field|ezselection_content(true)}
Returns array of the one selected, with identifier as key: array(<id> => <name>).
{$data_map.my_ezselection_multiple_field|ezselection_content}
Returns array of selected values, with identifier as key: array(<id> => <name>, […]).
ezobjectrelationlist_content¶
Summary¶
Alternative for getting ezobjectrelationlist content as a list of nodes, instead of an array which does not have the nodes.
Usage¶
field|ezobjectrelationlist_content
Parameters¶
Name | Description | Required | Default |
---|---|---|---|
field | eZObjectRelationList field from data_map. Do note that we do not pass in the content, and instead the entire field. | Yes |
Examples¶
{$data_map.my_ezobjectrelationlist_field|ezobjectrelationlist_content}
Returns an array of nodes, or an empty array if there is no content: array(eZContentObjectTreeNode)|eZContentObjectTreeNode.
Workflow event types¶
autopriority¶
Automatically sets the priority of new nodes to the maximum of siblings prirorities incremented by value of [AutoPriority]/PriorityIncrement set in swark.ini (default 10).
defertocron¶
Defers the workflow to the cron (background processing).
Custom operators¶
Swark also makes it easier to create custom operators.
Operators are detected from the INI file swark.ini. Adding a new operator only requires defining a new entry in the INI file under [Operators], this maps the template operator name to a PHP class that implements the operator.
For instance to expose the phpinfo() function we could do.
[Operators]
OperatorMap[phpinfo]=MyProject\PhpInfoOperator
Then create the PHP file and extend SwarkOperator, the base class will take care of all the cruft needed to define a template operator. The class must be accessible from the autoload system in PHP.
<?php
namespace MyProject;
use SwarkOperator;
class PhpInfoOperator extends SwarkOperator
{
// ...
}
The operator class then needs a constructor to initialize its operator name and its parameters (namedParameters), and a function to execute.
Constructor¶
The constructore defines the name of the template operator, this must match the name as specified in swark.ini. It also defines any parameters that it supports. Each parameter is a name with an optional default value.
For instance for our phpinfo operator we have one parameter which is empty by default, this matches the $what parameter for the phpinfo() function.
<?php
class PhpInfoOperator extends SwarkOperator
{
function __construct()
{
parent::__construct('phpinfo', 'what=');
}
}
Execute¶
The execute function takes in two parameters $operatorValue and $namedParameters. $operatorvalue corresponds to the value that is piped to the operator, and $namedParameters is the value(s) supplied as parameters using the names defined in the constructor. Any values returned from execute will be the return value from the template operator.
The phpinfo implementation is then as follows.
<?php
class PhpInfoOperator extends SwarkOperator
{
static function execute($operatorValue, $namedParameters)
{
if ($namedParameters['what']) {
$constants = array('INFO_GENERAL' => 1, 'INFO_ALL' => -1);
$what = $namedParameters['what'];
if (in_array($what, $constants)) {
phpinfo($constants[$what]);
return;
}
}
phpinfo();
}
}
An using it in an eZ template:
{phpinfo('INFO_GENERAL')}