SEM Labs

Handcrafted Pixels, Code & Title Tags

Foreach

Elements

The XFL foreach element repeats sections of an XFL document based on the result of a XPath query.

Dissection of the XFL Foreach Element

Syntax

Attributes

Attribute Value Description Required
select XPath query XPath query to execute on the data document Yes
always-show yes
no
will return the contents of the foreach element when no matching nodes were found when set to 'yes'. When no value is set, the XFL parser will ignore the foreach node No

Purpose of the XFL Foreach Element

The XFL foreach element is designed to repeat a section of an XFL document based on the number of elements returned by the XPath query in the select attribute. For example, a form that moderates comments on a blog will use the same form fields repeatedly for each comment. XFL foreach elements can be nested within each other to produce complex forms.

Basic Use of the XFL Foreach Element

In the below example, a multi-dimensional array is used to populate a form. It should be mentioned here that the XFL parser, converts this array into an XML document and as numbers cannot be used for XML element names, any integer keys in an array will be converted into an xfl-item element: <xfl-item key="int"><--! Content --></xfl-item>. See the data document section for more information. The xfl-item elements can then be iterated by an XFL foreach element to produce fields for each part of the array.

Basic Example

Source Array:

[name] = 'Tony'
[colours][0] = 'Red'
[colours][1] = 'Blue'
[colours][2] = 'Yellow'

The XFL parser will convert the array in the following data document

The following XFL document has been crafted to be populated with the data from the above array.

When the XFL document is parsed by the XFL parser, it will output the following HTML form:

First Dimension Example

When an XFL element iterates the first dimension of an array, the XFL parser will automatically prefix all form fields with the relevant value. This is carried on though multiple dimensions.

Source Array:

[0][name] = 'Tony'
[1][name] = 'Barry'
[2][name] = 'Taye'

XFL Document:

Produces the following form:

Using Always Show

Setting the always-show attribute to 'yes' on an XFL foreach element will output its contents once when its select expression doesn't return any elements in the data document.

Source Array:

In this example, no data source will be provided.

XFL Document:

Produces the following form:

Using Nested XFL Foreach Elements

The XFL parser supports infinite nesting of XFL elementss – that is XFL elements inside one another. This feature can be used to create forms with ease that would otherwise be difficult to process.

Source Array:

0[company] = 'Company A'
0[clients][name][0] = 'Client A'
0[clients][name][1] = 'Client B'
0[company] = 'Company B'
0[clients][name][0] = 'Client 1'
0[clients][name][1] = 'Client 2'

XFL Document:

Produces the following form: