Manual

Full source code online documentation HERE.

1. Installation

Download the figdice sources.
Unzip to a folder accessible to your PHP application.

When unzipping, you should keep the containing folder 'figdice-<version>'.

1-1. Getting started

  1. Add the full path to 'figdice-<version>' to your include path (using either set_include_path, or the include_path directive in php.ini).
  2. In your PHP script, include the \figdice\View class:
    require_once('figdice/\figdice\View.php');
  3. Create a View object:
    $view = new \figdice\View();
  4. Load a template file:
    $view->loadFile('my_figs/hello-world.html');
  5. Display the result:
    echo( $view->render() );

If your template contains calls to fig:feeds you must instanciate one ore more Feed Factory beforehand.
You should also set up the Logging Delegate, and temp folder for Internationalization cache, if you use them.

More resources can be found in the Tutorials section.

2. The FigDice XML markup

A FigDice template is primarily an XML file, which contains a piece of HTML or an entire HTML document, with some restrictions such as the need to comply to well-formed XHTML.
FigDice defines a namespace called fig: by default, which can be renamed by declaring it in the root node of the XML document:

xmlns:fig="http://www.figdice.org/"

The tags and attributes of FigDice make it possible to control the behavior of the template rendering engine to generate the resulting output according to your logics and data.

Tags and attributes

In the following:

  • static means that the value is passed as is.
  • evaluated means that the value is a FigDice expression which is evaluated before being passed.
  • ad hoc means that the value is static, but can also contain evaluated sub-expressions, in {curly braces} (see The ad hoc evaluation).

NB : In FigDice, the plain HTML attributes are always ad hoc.

  • This tag positions as the child of any HTML tag. Its role is to declare an additional attribute to the parent tag, possibly conditionally (see fig:cond and fig:case), and whose value will be dynamic.

    An HTML tag can contain several fig:attr children, but they all must declare unique attribute names, or be mutually exclusive through FigDice conditions.

    An attribute that was defined inline in the parent tag cannot be redefined using a fig:attr child.

    Attributes :
    name required static
    The name of the attribute that the run-time must add to the parent tag.
    value optional evaluated
    A FigDice expression which provides the resulting value for the attribute in the parent tag.
    If omitted, the output of contents of the fig:attr tag is used.
    Example :
    FigDice template:
    <div id="div1">
      <fig:attr name="class" value="'Line_' + color" />
      <span>Hello</span>
    <div>
    			
    Output:
    (assuming that the variable color contains 'red' in the current context)
    <div id="div1" class="Line_red" >
      <span>Hello</span>
    <div>
    			
  • fig:auto attribute

    Whenever you need to have complex attributes on a tag, or conditional attributes, you must use a fig:attr children.
    But, despite they do not produce output, they are considered as children of your parent tag, thus becoming a container. Therefore, it will be rendered with an opening and closing tags.

    Yet, some XHTML elements must always be empty, self-contained nodes, immediately closed with / in the end of the tag: for example <br/>, <img ... />, <hr/>.

    To tell FigDice the tag is self-closing, despite children tags in the template, use the attribute fig:auto.

    See also: fig:void.

    Value:
    Evaluated to true: indicates that the tag is self-closing.
    Note: The tag will be rendered self-closing only if its contents after rendering, is effectively empty, regardless of the value of fig:auto.
    Example :
    FigDice template:
    <img id="img1" fig:auto="true">
      <fig:attr name="class" value="'Line_' + color" />
    </img>
    			
    Result:
    (assuming that color contains 'red' in the current context)
    <img id="img1" class="Line_red"  />
    			
  • fig:call attribute
  • fig:case attribute

    This attributes operates in a similar way to fig:cond, but additionally it enables to build a group of mutually exclusive conditions among sibling tags, much like the switch / case construct of the C language.

    A group of mutually exclusive conditions is automatically made up, as soon as several sibling tags (i.e. immediate children of the same parent) bear the fig:case attribute. The remaining siblings, which do not bear this attribute, are not part of the group.

    The engine renders only the first tag whose condition is satisfied, within the group. All other members of the group are discarded.
    All other siblings which are not part of the group (i.e. without the fig:case attribute) are rendered regularly.

    The default construct of the C language can be achieved by adding to the group a final tag with condition fig:case="true". Then, if no previous condition was satisfied, this last member will be.

    It is possible to nest several groups, at different levels of depth in the XML tree. Each group operates independently, within the node space of its parent tag.

    Note that each condition can test anything. Unlinke the switch/case construct, where one single expression is tested against several values, here each fig:case attribute can use a different condition. The only rule is that, as soon as one is satisfied, in the order of the DOM, then the group finishes.

    Value:
    Evaluated to true: indicates that the tag should be rendered with all its contents. The other members of the group are then short-circuited.
    If false, the engine skips the tag and all its contents, including active directives such as fig:feed or fig:include.
    Example :
    <div>
    	Only one situation below will appear:
    	<span fig:case="price == 20"> Cheap </span>
    	<span fig:case="count(items) == 0"> Empty </span>
    	<span fig:case="true"> Default case </span>
    
    	<span> And this one always shows! </span>
    </div>
    			
  • This tag imports arbitrary unparsed contents from an external file.
    The specified file is integrated as is at the position of the current tag in the template. It can be of any type, text or binary. In particular, it does not have to be an XML file.

    Attributes :
    file required static
    The name of the file to load. The path must be relative to the current FigDice file.
  • fig:cond attribute

    This attribute tells the engine if the tag must be processed (rendered) or skipped.
    You use fig:cond to allow for application logic, to decide when a tag and its descendents should be treated. The value of fig:cond is an expression that must evaluate to true or false.

    It is possible to apply fig:cond to a fig:attr tag: in this case, if the condition evaluates to false, the dynamic attribute is omitted.

    When applied to a tag which also has the fig:walk attribute, then the condition is tested on each iteration, rather than on the outer loop tag. In this case, the expression of the condition must be formulated relative to the current context of the iteration element.

    Value:
    Evaluated to true: indicates that the tag should be rendered, along with all its descendents.
    If false, the engine bypasses the tag and all its contents, including any active tags such as fig:feed or fig:include.
    Example :
    FigDice template:
    <div id="div1">
      <fig:attr fig:cond="/some/data == 2" name="class">Line_Double</fig:attr>
      <span fig:cond="/some/data == 3">Hello</span>
    </div>
    			

    Output:
    (assuming /some/data is 2)
    <div id="div1" class="Line_Double">
    </div>
    			
    Output:
    (assuming /some/data is 3)
    <div id="div1" >
      <span>Hello</span>
    </div>
    			
  • Imports a Language File in the current template.
    See 5. Internationalization.

    Attributes :
    file required static
    The name of the language file, relative to the Translation Path and Language folders specified to the View through its methods setTranslationPath and setLanguage.
    name required static
    The alias you assign to the language file within the template, for future reference in fig:trans tags.
    source optional static
    This attribute specifies the language code for which you wish to avoid the loading of the dictionary file.
    If the View's language is set to this language code, the dictionary won't load and all the fig:trans tags in your template, which use this dictionary (by its alias) will skip the look-up phase, and render their inner content directly.
  • It is with this tag that the template invokes a Data Provider (Feed).
    The system instanciates the Feed object given its class name, specified in attribute class.
    For more information on loading and instanciation of the provider, see classes: \figdice\Feed and \figdice\FeedFactory.

    The result of the call to the provider object is added to the Universe of data, as a root branch with name specified in attribute spécifié dans l'attribut target.

    All other attributes of tag fig:feed are passed as parameters to the Feed object.

    Attributes :
    class required static
    The name of the class to invoke. FigDice queries the chain of registered \figdice\FeedFactory objects, for handler of this particular class.
    target optional static
    The root name by which the loaded data become accesible to the template. The data remain available in the rest of the template execution, immédiately after the fig:feed tag.
    If the root name already exists in the Universe, its contents is replaced.
    If the target attribute is omitted, the result of the feed is not captured, but the instance is still executed.
    (any other attribute) optional evaluated
    All other attributes are evaluated and then passed as parameters to the \figdice\Feed object. See the corresponding section for more details on how to retrieve the parameters.
    Attention: these additional attributes are evaluated, which means that they are expressions. Therefore, although you can pass numeric literals directly, you should be advised that if you wish to pass string literals they should be wrapped up in single-quotes.
    Example :
    <div>
    	<!-- Load user info for userID=12 into "user" top-level key: -->
    	<fig:feed class="UserFeed" target="user" userID="12" />
    
    	Your email is: <span fig:text="/user/email" />
    
    </div>
    			
  • fig:filter attribute
  • Includes another template file.
    The included file must be a valid FigDice template, which can itself include other files.

    This is an auto-closed tag. It cannot have inner contents.

    The inclusion is realized at execution-time. The included file is parsed and rendered as the fig:include tag is encountered, as if the file contents were pasted inline in place of the tag.
    Consequently, the Context (Universe, Iterations, Macros etc.) is continued in the included file.

    In the current version, there is no run-time check to avoid infinite inclusion loops.

    Attributes :
    file required static
    The file to include. It must be a relative path from the caller template.
    Example :
    <div>
    	<fig:include file="../header-menu.html.xml" />
    	<fig:include file="reporting/macros.html.xml" />
    </div>
    
    			
  • fig:macro attribute

    A macro is very similar to a subroutine in any programming language: it is a block identified by a name, which you invoke with parameters, in order to produce output.

    Quite naturally, a FigDice macro is a piece of XML tree.

    It is defined by its name:

    	<div fig:macro="MyMacro"> ... </div>

    In this statement, the FigDice engine defines the macro called MyMacro. It does not render this div tree in place: rather, the definition itself produces no output, but the macro can be called from any place in the view, by invoking:

    	<div fig:call="MyMacro" />

    The effect of this call, is that FigDice then behaves as if you had pasted inline the piece of tree defined by the macro.

    Unlike the plug/slot mechanism, the macro call must be already defined by the time of the call instruction -- potentially in an included file.

    Unlike the plug/slot mechanism, where the plug is rendered using the global data universe available at the end of rendering, a macro call is executed with the current data context.
    In particular, a relative path in a FigDice expression inside a macro, refers to the local context of data of the fig:call instruction.
    This makes it possible to call a macro from within a fig:walk, for example.

    Besides, a macro accepts calling arguments: every non-fig attributes specified at the fig:call tag level, are passed as arguments to the macro. They are added to the local context, and can be used in the macro as relative names in FigDice expressions.

    Example:
    	<div fig:call="MyMacro" myparam=" /myVariable " />

    will invoke the rendering of the macro MyMacro, by pushing on the stack of available data the relative symbol "myparam".

    You can pass any number of named arguments. Keep in mind that their values are FigDice evaluated expressions. In particular, arguments can even be complex data structures or objects, as received from a Feed.

    Additionally, you can pass more complex variables to a macro call, by using the special child tag: fig:param.

  • Makes an alias to a location in the Universe, or assigns an arbitrary computed value to a variable.
    The alias is added to the root of the Universe.

    Attributes :
    target required static
    The name of the alias. If it already exists, it is replaced.
    value optional evaluated
    The expression to calculate and to place in the alias.
    If this attribute is omitted, the contents of the tag is calculated, then the result is assigned as text value to the variable.
    Example :
    
    <fig:mount target="shortcut" 
    	value="/long/path/2/symbol" />
    
    <fig:mount target="i" value="/i + 1" />
    
    <fig:mount target="myString">
    	any piece of template here, 
    	including HTML and FigDice tags <span fig:text=" /shortcut " />
    </fig:mount>
    
    			
  • fig:mute attribute

    This attribute lets you specify whether the envelope of the bearing tag must be rendered or ignored.
    The inner contents of the tag are always rendered: only the rendering of the tag itself, with all its attributes, is controlled by fig:mute. The value of fig:mute is an expression evaluating to true or false.

    Value:
    Evaluated to true: the engine will only produce the inner contents of the tag, omitting the tag itself and its attributes. If false, the outer tag is output, with all its attributes.
    Example :
    FigDice Template:
    <div fig:mute="true" id="div1" >
      <span>Hello</span>
    </div>
    
    <div fig:mute="2 * 0" id="div2" > <span>World</span> </div>
    			
    Result :
      <span>Hello</span>
    
    <div id="div2"> <span>World</span> </div>
    			
  • In addition to passing plain named attribute-like arguments to a macro when invoking fig:call, you can pass more complex variables to a fig:macro, by using the special child tag: fig:param of parent fig:call, as in:

    	<div fig:call="MyMacro">
    	  <fig:param name="country" value=" 'FR' " />
    	</div>

    The same syntax is used to pass complex parameters to the fig:trans tag.

    You can pass any number of fig:param tags, with any name. You can put conditions fig:cond and fig:case on the fig:param tags in order to pass arguments conditionnally.

    Just as for fig:attr attributes, the value of a fig:param can be specified inline with the "value" attribute , or you can give inner XML FigDice content to the associated argument. The content is evaluated in place and its result is passed to the macro.
    Keep in mind that the "value" attribute of fig:param is a FigDice evaluated expression, just as that of the fig:attr tag.

    You can mix inline parameters and fig:param children.

  • fig:plug attribute

    You use fig:plug in order to inject contents into a fig:slot defined elsewhere.

    The rendered contents of the fig:plug replace the fig:slot tag of corresponding name. It is not rendered in the current location of fig:plug.

    You can provide content to a slot before defining it. It can even be defined in a sub-template which you will include later in the document.

    If you have injected some contents into a slot that cannot be found in the end of the rendering, your injected contents are discarded.

    Important note: the Plug/Slot matching is made in the end of the rendering.
    In particular, be careful of the state of the Universe when writing your plugs: the available data may not be those that were available in the initial location of the plug in your document.

    Value:
    Static: the name of the fig:slot placeholder into which to inject your contents.
    fig:append
    Evaluated: An additional attribute can be declared along with the fig:plug attribute.
    It indicates whether the previous contents must be retained or replaced, in case of multiple injections into the same placeholder.
    If true, the plugged contents are appended to whatever already injected contents in the slot.
    Note that in any case, the plug replaces the slot tag, rather than fill it up. The outer slot tag is not rendered.
    Example :
    	<div fig:plug="docTitle">
    		<!-- Provide now the actual Page Title,
    		    for which there is a placeholder in the <head> section. -->
    		<span fig:mute=" true  " fig:text=" /article/title " />
    	</div>
    			
  • fig:slot attribute

    This attribute declares a named placeholder at the current position in the XML document.

    Anywhere in the document or its parent template or included sub-templates, you can provide replacement for the placeholder, by calling the fig:plug attribute. Then, all the rendered contents of the tag with fig:plug will be injected at the fig:slot location in the resulting document. The slog tag itself is removed from the document. That is, plugs bring replacemement for the slot tag, rather than actual content.

    The definition of the slot can occur later than the plug providing contents for it.

    Plug/Slot matching is made in the end of the rendering.

    If no plug brings contents to a slot, the slot tag itself is rendered, then acting as default content. If you do not wish to have default content, mute the tag and leave it empty.

    Value:
    Static: the name of the placeholder, for future reference by fig:plug.
    Example :
    	<head>
    		<!-- Placeholder for Page Title,
    		    which will be filled by further logics -->
    		<title fig:slot="docTitle" />
    	</head>
    			
  • fig:text attribute

    This attributes provides dynamic contents to the bearing tag.

    Its value is an expression whose result is used as the contents of the tag, in place of all its children.
    All the children are removed, including active tags such as fig:include or fig:feed.

    Value:
    Expression evaluated and output as the contents of the tag. The outer envelope itself, is preserved.
    Example :
    Template:
    <div>
    	<span class="myclass" fig:text="/user/email">
    		Placeholder text <i>here</i>, 
    		will be removed and replaced by the fig:text value.
    	</span>
    </div>
    			
    Output:
    <div>
    	<span class="myclass" >
    		user@domain.com
    	</span>
    </div>
    			
  • This tag inserts a translatable string, given the specified key and dictionary.

    You can pass parameters by either extented attributes, or fig:param children.

    You can specify an optional source language attribute, which will save the engine from attempting to translate if you specified inner content to fig:trans in this language (but will still perform the parameter substitution).

    Attributes :
    source optional static
    The language of the inline content.
    dict required static
    The alias of the dictionary, loaded by fig:dictionary in which to look for the key.
    key required static
    The key for which to search internationalized version in the View's target language.
  • fig:walk attribute

    This attribute iterates on a collection (indexed or associative array).

    The carrier tag, and all its descendents, is repeated at run-time as many times as there are elements in the array.
    Each iteration runs in the context of the current element, whose properties (keys) thus become directly accessible by their relative name.

    A number of built-in functions allow you to locate within an iteration: odd(), even(), first(), last(), position(), key().

    The data context is restored at the end of iteration.
    During an iteration, the current element itself (scalar or collection) is accessible by using the special path: "." (dot).

    You can nest as many fig:walk as necessary: each time, the context will switch to the current element of the running walk. You can use the "../" notation in your Path in order to refer to the context of the parent loop.

    If the tag also has a condition fig:cond, the fig:walk prevails on it. The condition is evaluated inside the loop, at each iteration, in the context of the current iteration item. To achieve a global condition on a tag which also have a Walk loop, you must enclose it in a parent tag and place the condition on it. If you do not wish to show this wrapping tag, mute it with fig:mute.

    Ad-hoc evaluations are also computed on each iteration.

    Value:
    Evaluated : Path expressing the array on which to iterate.
    Example :
    
    <!-- Load a collection of products 
    	Each item has two properties: number, and price. -->
    <fig:feed class="ProductsFeed" target="products" category=" 'Garden' " />
    
    <table>
    	<thead>
    		<tr>
    			<th>Product number</th>
    			<th>Price with tax</th>
    		</tr>
    	</thead>
    	<tbody>
    		<!-- Iterate on each item in the products array 
    			and repeat the <tr> tag and its descendents: -->
    		<tr fig:walk="/products">
    			<!-- Local properties of the current item are accessed 
    				with relative paths (number, price). -->
    			<td fig:text="number"></td>
    			<!-- Properties outside the current item are accessed 
    				with absolute paths (/constants). -->
    			<td fig:text="price * /constants/taxRate"></td>
    		</tr>
    	</tbody>
    </table>
    
    			

3. The expressions

Expressions are what you place in FigDice evaluated attributes and in curly braces { } in ad-hoc blocks.
They are evaluated by the system during the template run-time. An expression leads to one single resulting value, which can be of any data type.

FigDice implements a powerful expression engine based on the principle that the author of a template must not be concerned with the nature of the data, nor be bothered with any programming languages syntax.

This principle results in a very simple yet robust syntax, which provides a way to use homogeneous data available in the Universe, perform operations with them, control the iterations of loops, etc.

An Expression is made of arithmetical, logical and string operations on data elements (Paths) present in the Universe, and on literal strings, numerical and boolean values, as well as Function calls.

3-1. Universe

The Universe is the entire set of data made available to a FigDice template.

It is organised in a tree of key-value pairs, where each value can be a dictionary collection on its own. FigDice expressions use the Path notation to refer to structured data present at any level in the Universe.

The Universe is constructed by:

  • Using the fig:feed tag inside the template, to bring data from the outside world,
  • Using the fig:mount tag inside the template, to rearrange data that are already contained in the Universe,
  • Calling the mount method of the \figdice\View class from the outside world to push data into the template.
These three ways lead to the creation of top-level keys in the Universe.

The Universe is shared with all the included sub-templates during the rendering cycle.
An addition to the Universe, by the above "inside" methods, at any inclusion level, becomes also available to the parent templates and all subsequently included files.

3-2. The Path

The Universe contains data that the template can use.
These data are structured in a descending tree of key-value pairs, like a multi-level-depth PHP associative array, very similar to the entries in a filesystem tree.

Therefore the Template's expressions interrogate the Universe's data by using a filesystem-like, slash-separated notation:

/path/to/some/data

The keys are case-sensitive.

Integer numbers are valid keys, especially when accessing the elements of an indexed array:

/books/3/title

In order to access top-level keys (see Universe ), the Path starts with a leading Slash "/".
For sub-keys of the current context, in an iteration or in a macro call, the Path directly starts with the sub-key name.

author/firstName

If a requested key does not exist, the result is empty.
There is no error in descending an non-existing path: querying sub-keys of a non-existing path returns empty sucessfully.

There are two special keys, used to access the current item in an iteration, and the parent loops' items in nested fig:walk loops: the simple-dot ".", and the double-dot "..".

The simple-dot, is generally used to express the current iteration when it contains an immediate value ; that is, inside a fig:walk where each value is not a dictionary on its own, but rather a scalar value which you wish to use in fig:text for example.

	<!-- array('red', 'green', 'yellow') -->
	<tr fig:walk="/colors">
	  <td fig:text="."></td>
	  <!-- <td>red</td>
	       <td>green</td>
	       <td>yellow</td> -->
	</tr>
	

The double-dot lets you go up one loop's level, and then access the sub-keys of the parent item from here.

 <!-- Outer loop on books -->
 <tr fig:walk="/books">
   <td fig:text="author/name"></td>
   <td>
     <ul>
       <!-- inner loop on book's chapters -->
       <li fig:walk="chapters">
         <!-- Each iteration of the inner loop displays
         a field from the running item (chapter name),
         and a field from the outer loop's current 
         item (book's title). -->
         Chapter <span fig:text="name"/>
         Book <span fig:text="../title"/>, 
       </li>
     </ul>
   </td>
 </tr>
	

Path and Objects

A Feed class can also return objects, in addition to plain associative arrays. On objects, the Path interprets key names as public getter methods of the object, according to the following naming pattern:

For key: keyName
getter method must be:
public function getKeyName() or
public function isKeyName()

The Object oriented way has higher priority over the associative array way. When both a getter method and a public property exist for the interrogated key, the getter method is used. If both get...() and is...() are defined on the object, the get method is used by the Path expression.

Attention: the Path access only public members on objects. If the object has a non public member corresponding to the key name, the Path will return null.

Aggregate arrays

There is a special case when working with zero-based indexed arrays: when you access the name of an item's key directly below the array name, instead of accessing the key relatively in an iteration, or through the item's index number, you actually construct an ordered set of all the values contained in that same sub-key of all the items in the array.

Example:

In the following JSON-noted indexed array, every item is an object presenting a common member «commonProperty».

/data = [
	{ commonProperty: 3 },
	{ commonProperty: 5 },
	{ commonProperty: 4 }
]

Then the result of sum( /data/commonProperty ) is 12.


This special usage of the Path makes it possible to work with Aggregate functions, either built-in or user-defined.

3-3. Keywords and operators

Below is the list of the keywords and operators supported by the FigDice Expression system. Just as in mathematical terms, you can use parentheses ( ) to group sub-expressions or to control operation priority.
+ (plus sign) Numerical addition, String concatenation, Unary positive sign.
- (minus sign) Numerical substraction, Unary negative sign.
* (star sign) Numerical multiplication.
div Numerical division (the Slash symbol has a different meaning in FigDice: see Path). Does not raise a Division by Zero error: rather, returns false.
true The constant True.
false The constant False.
== Test of Equality.
!= Test of Non-equality.
lt Less Than (equivalent to < in many programming langages, but the < symbol is not valid in XML attributes.)
lte Less Than or Equal (equivalent to <= in many programming langages, but the < symbol is not valid in XML attributes.)
gt Greater Than (equivalent to >= in many programming langages, but the > symbol is not valid in XML attributes.)
gte Greater Than or Equal (equivalent to >= in many programming langages, but the > symbol is not valid in XML attributes.)
and Logical And operator
or Logical Or operator


3-4. Iterations, context

3-5. The ad-hoc evaluation

The value of static attributes is used as is, without modification.

The evaluated attributes are handled by the FigDice Expressions engine, and it is the result of the evaluation that is used as the attribute value.

The third form of attributes is called ad hoc: it is normally static attributes, but which may contain evaluated parts, which you place between braces { }. The engine evaluates each expression in braces, in order of appearance, and replace the term in the static string with the result of the evaluation, to build up the final attribute value.

	<option id="opt_{ position() }_country"
		value="{countryCode}" fig:text="countryName" />
					

Ad hoc expressions behave exactly the same as standard FigDice expressions. In particular, you can use built-in functions, user-defined functions, and any path and operator.

The number of evaluated parts in an ad hoc attribute is not limited.

The attributes of fig: tags are either static, or evaluated.
The direct parameters in macro calls, ie the additional attributes of HTML tags that carry the fig:call attribute, are evaluated. All other attributes of the document (in particular the usual attributes of legitimate HTML tags) are ad hoc.


3-6. Dynamic Path Components

When writing a Path, you specify the way to reach the value at a particular sub-key in the Universe. Each path component, separated by a slash « / » represents one more level in the depth of the data tree.

Yet sometimes you do not know in advance the name of one key, at template-authoring time, but this key itself is in fact the result of another expression.

For these situations you can use a Dynamic Path Component, by wrapping up the secondary expression in square braces « [ ] » in your Path:

/path/to/[ computed/key ]/data

This construct is particularly useful when presenting pivot tables, where you need to nest two loops and the keys of the inner collection come from values in the outer collection.

Dynamic Path Components can contain more dynamic parts themselves.
The number of Dynamic components within a path is not limited.


3-7. Built-in Functions

In the FigDice Expression language you can call functions, using a syntax similar to that of the C language.

All the arguments are Expressions. Depending on the function's semantic, they can be of various types: strings, numeric, boolean, or even data collections or XML nodes.

During a function call, all the arguments are evaluated beforehand, and then passed to the function.

Functions names are case-sensitive.

In addition to the Built-in Functions, you can develop your own User-defined functions using the provided API.

Functions operating on collections

  • count

    Syntax: count ( <indexed array> )

    Returns the number of items in the specified collection.

Functions operating on iterations

These functions do not have any arguments. They can only be called within a fig:walk loop.
They run on the current item of the iteration, and there is no way to call these functions on outer loops' items from within a nested loop.

In nested loops, if you need to use iteration functions on outer loop's items, you must capture their values using fig:mount.

  • even

    Syntax: even ( )

    Returns true when the 1-based position of the current iteration is an even number.
    Returns false otherwise.

  • first

    Syntax: first ( )

    Returns true at the first iteration of a loop.
    Returns false in all other iterations.

  • key

    Syntax: key ( )

    When the loop is running on an associative array, returns the key of the current item.

  • last

    Syntax: last ( )

    Returns true at the last iteration of a loop.
    Returns false in all other iterations.
    Equivalent to: not( first() )

  • odd

    Syntax: odd ( )

    Returns true when the 1-based position of the current iteration is an odd number.
    Returns false otherwise.
    Equivalent to: not( even() )

  • position

    Syntax: position ( )

    Returns the current 1-based index of the running iteration.

Functions operating on scalar values

  • const

    Syntax: const ( expression )

    Looks up the PHP const value defined by the specified name, and returns its value.

    The lookup is guarded: a undefined const will not cause failure (but returns false instead).

    Class consts can be looked up with the scope operator '::', as in:

    const ( 'MyClass::MYCONST' )

    The mechanism of evaluation of the litteral outcome of the expression, as the name of a constant, is highly language-dependent.

  • default

    Syntax: default ( tentativeExpression, defaultValue )

    Use the specified tentativeExpression, unless it evaluates to false, in which case use the defaultValue instead.

  • format_number

    Syntax:

    format_number ( number [, decimals [, decPoint [, thousandSep ]]] )

    Returns a numeric value formatted with the specified number of decimal digits, symbol for decimal point, and symbol for thousands separator.
    The first argument is mandatory, the others are optional.

    decimals defaults to 2.
    decPoint defaults to comma ','.
    thousandSep defaults to space ' '.

  • format_timestamp
  • GET

    Syntax: GET ( string )

    Returns the value of the specified URL parameter from the HTTP GET request.
    Returns empty if the parameter does not exist.

  • if

    Syntax: if ( condition, thenExpression, elseExpression )

    This function acts as the ternary operator.
    If condition is true, returns thenExpression.
    If false, returns elseExpression.

  • not

    Syntax: not ( expression )

    This function is the logical Not operation.
    It evaluates the logical expression and returns it negation.

  • php
  • substr
  • xml
  • xpath

Functions performing aggregations

Aggregate functions are a particular type of functions. Their argument is neither a collection, nor a field: it is a special notation which makes it possible for FigDice to aggregate the values of the same sub-key in all the items of an indexed array.

Example:

    <fig:feed class="InvoicesFeed" target="invoices" />
    <!-- /invoices is a 0-based indexed array
        whose every item has an "amount" key. -->
    <div fig:text=" sum ( /invoices/amount ) " />
		

In order to access a particular item's field by index, you would use:

    /invoices/5/amount

(for the 6th element of the 0-based array /invoices)

The special notation for aggregate functions skip the index component, and specifies directly the field of interest below the array name.

The indexed array must be zero-based.

  • average

    Syntax: average ( <indexed array>/<common key> )

    Returns the average value in the <common key> field of all the items in <indexed array>.

  • sum

    Syntax: sum ( <indexed array>/<common key> )

    Returns the sum of the values in the <common key> field of all the items in <indexed array>.

4. Classes and interfaces

Public classes and interfaces by name

4-1. Views

\figdice\View

The View is the entry point of the FigDice rendering engine.

The first step consists in creating a \figdice\View object, then you register the Factories for your Feeds, Filters and Functions. Next, you indicate to your \figdice\View instance to load an XML template file. Finally, you call the rendering method which returns the output.

$view = new \figdice\View();
$view->registerFeedFactory( $feedFactory );
$view->loadFile( $templateFilename );
echo $view->render();
			

The method render of class \figdice\View analyzes the loaded template file, and starts the rendering engine.
It handles automatically the loading of included sub-templates with fig:include tags.

class \figdice\View

public function loadFile ( string $filename )
returns void

public function mount ( string $mountingName, mixed $data )
returns void

public function registerFeedFactory ( \figdice\FeedFactory $factory )
returns void

public function registerFunctionFactory ( \figdice\FunctionFactory $factory )
returns void

public function render ( )
returns string

public function setFilterFactory ( \figdice\FilterFactory $factory )
returns void

public function setLanguage ( string $language )
returns void
Specifies the target language code in which you wish to translate the fig:trans tags or your templates.
This language code must correspond to a subfolder of the Translation Path (See 5-1. Dictionaries).

public function setTempPath ( string $path )
returns void
Specifies the folder in which the engine will be able to produce temporary files, for pre-compilation purposes.
The engine will not attempt to use cache-based optimization features if you leave this property blank.

public function setTranslationPath ( string $path )
returns void
Specifies the folder in which you provide all the Dictionary files, each in its language code's subfolder.
See 5. Internationalisation.

4-2. Data Providers

\figdice\Feed

The Feed is the data provider for the View. It makes the link between the data managed by the application, and the contents to serve to the client.
The Feed works in the Presentation Layer.

abstract class \figdice\Feed

protected function getFigFile ( )
returns string

protected function getParameter ( string $name )
returns mixed, null if key not found

protected function getParameterBool ( string $name, boolean $default = false )
returns boolean

protected function getParameterInt ( string $name, int $default = 0 )
returns int

protected function getParameterString ( string $name, string $default = '' )
returns string

abstract public function run ( )
returns mixed

When the view \figdice\View encounters a fig:feed tag, it instanciates an object whose class is specified by the class attribute. This class must inherit from class \figdice\Feed.
Then the engine passes to the object its calling parameters, and executes its run method.
The result of run is added to the Universe of the view, at root level, under the name specified by the target attribute of fig:feed.

A new \figdice\Feed object is instanciated at each call to fig:feed, even if one same class is invoked multiple times in the same View.

The Feed instance receives the key/value pairs passed by the Template through the extended attributes of the calling fig:feed tag. Every attribute which is not in the fig: namespace, and apart from class and target, bring values to the Feed object, which it can query with the getParameter methods family.
The String, Int and Bool versions of the method allow a safe typecast while specifying a default value in case of absence of the key or if the underlying value is not of the expected type.

Example :
template.xml

<!-- Load a collection of products in the 
	specified category: 'Garden'. -->
<fig:feed class="ProductsFeed" target="products" category="'Garden'" />

			
ProductsFeed.php
class ProductsFeed extends \figdice\Feed {
	...
	public function run() {

		$categoryName = $this->getParameterString('category');
		// Fetch products from DB for category $categoryName
			...
		return ... 
	}
	...
}
			

\figdice\FeedFactory

When it is time for the system to instanciate on demand a Feed object as per class name specified in fig:feed tag, the child class of \figdice\Feed is not necessarily already loaded in the Class Space of the program. Moreover, in general your Feed classes will have particular features which makes it necessary for them to dialog with the Controller, unique owner of the View. For example this is the case when the Feed must obtain from the Controller the database connection string, or some session information.

public function create ( string $className, array $attributes )
returns \figdice\Feed, null if specified \figdice\Feed subclass is not handled by this factory

Therefore, the View obtains instances of the Feed classes through the use of Factories, implementing the \figdice\FeedFactory interface.
Each \figdice\FeedFactory instance is responsible with instanciating one set of \figdice\Feed classes, by their names.

Before rendering the view, the Controller registers all the \figdice\FeedFactory instances that it may have to use. Then, during the processing, when a fig:feed tag is executed, the View queries every registered \figdice\FeedFactory in turn, until it obtains an instance of the child class of \figdice\Feed specified by the class attribute.

You construct instances of \figdice\FeedFactory and you register these instances into the View. You can construct your \figdice\FeedFactory objects freely according to your needs, depending on the nature of the \figdice\Feed subclasses that they handle. In particular, they should maintain all the necessary information to enable communication between the \figdice\Feed instanciated on demand, and the Controller or any other component of the application.

4-3. Filters

4-4. Functions

4-5. Logging

5. Internationalization

FigDice provides a mechanism for key-based translation of all the text contained in your templates.

All you have to do, is indicate where in your templates the internationalizable messages are located, by enclosing them in fig:trans tags.

Language files are organized in XML dictionaries of key-value entries.

A fig:trans tag indicates a dictionary name, the key of the message to translate, and optional named parameters in the shape of inline attributes of fig:param children tags (same syntax as in fig:call).

Examples: FigDice Template
	<!-- Import two dictionaries into my current template: -->
	<fig:dictionary name="Product" file="product.xml" />
	<fig:dictionary name="Errors" file="common/errors.xml" />

	<!-- Display a translated message: -->
	<fig:trans dict="Product" key="PRODUCT_DESCRIPTION_COLUMN" />

	<!-- Display a translated message with a parameter: -->
	<fig:trans dict="Errors" key="MINIMUM_CHARS_EXPECTED" minChars=" 20 " />

In the dictionaries, the parameters of an entry are usable by their name, enclosed in curly braces:

Example: Dictionary
	<entry key="MINIMUM_CHARACTERS_EXPECTED">
		Please enter at least {minChars} characters.
	</entry>

The entries of a dictionary can contain any HTML parts:

	<entry key="MINIMUM_CHARACTERS_EXPECTED">
		Please enter at least <b>{minChars} characters</b>.
	</entry>

Additionally, a fig:trans tag can contain direct contents, for two purposes:
- avoid to create an explicit dictionary file for your default language,
- provide default value for a key not found.

Example:
	<fig:trans dict="Errors" key="MINIMUM_CHARS_EXPECTED" source="en" minChars=" 20 " >
		Please enter at least <b>{minChars}</b> characters.
	</fig:trans>

This example shows the "source" attribute, which tells the language of your direct content.
This way, if this language is the same as that of the View, the engine will not try to look up the key. Rather, it will immediately use the specified content.

5-1. Dictionaries

The structure of a Dictionary XML file is:

	<fig:dictionary language=" your language code " >

		<entry key=" a key ">  a translation  </entry>
		<entry key=" a key ">  a translation  </entry>
			...

	</fig:dictionary>

All the Dictionary files are organized in the following folder structure:

  lang
    |- languageCode
    |    |- file.xml
    |    |- file.xml
    |    |- file.xml
    |- languageCode
    |    |- ...
    |- languageCode
    |    |- ...
		
	

where lang is the folder you specify in the \figdice\View's setTranslationPath method, and the various languageCode subfolders are the values you give to setLanguage method before rendering the View.

5-2. Caching

For efficiency purpose, FigDice can compile the XML dictionaries into PHP serialized data.

If you specify a Temp Path to the \figdice\View object through its setTempPath method, your dictionary files get compiled on the fly the first time they are used, or if the source file has been modified since.

6. Error handling