Built-in scripting functionsBuilt-In Functions
Optional parameters for functions will be shown in square brackets in this article. If parameters have default values they will be shown in the usage string.
Most functions are available in JavaScript as well (exceptions are marked as such). Function names containing an underscore are also made available in mixedCase (CamelCase beginning with a lowercase character)
This chapter covers the following topics:
Boolean Functions
keyboard_arrow_rightkeyboard_arrow_downand()
Returns the logical AND result of the given boolean values.
Usage
and(boolean1, boolean2,...)
Examples
${and(true, false)}
false
keyboard_arrow_rightkeyboard_arrow_downempty()
Returns a boolean value that indicates whether the given object is null or empty.
Usage
empty(obj)
Notes
Before the Structr 2.1 release this method did not work on collections/arrays. If you are running an older version of Structr and want to determine if a collection is empty, use
gt()
in combination withsize()
for that.
Examples
${empty("")}
${empty("test")}
${empty(find("User"))}
${empty(find("NonExistentType"))}
true
false
false (if at least one user exists)
true
keyboard_arrow_rightkeyboard_arrow_downequal()
Returns a boolean value that indicates whether the values are identical.
Usage
equal(val1, val2)
Notes
eq()
is an alias forequal()
Examples
${equal(2, 3)}
false
keyboard_arrow_rightkeyboard_arrow_downgt()
Returns a boolean value that indicates whether the numerical value val1 is greater than the numerical value val2. This method tries to convert its parameter objects into numerical values, i.e. you can compare strings numerically. It is often used in conjunction with size()
to determine if a collection is empty or not.
Usage
gt(val1, val2)
Examples
${gt(1, 2)}
false
keyboard_arrow_rightkeyboard_arrow_downgte()
Returns a boolean value that indicates whether the numerical value val1 is greater than or equal to the numerical value val2. This method tries to convert its parameter objects into numerical values, i.e. you can compare strings numerically.
Usage
gte(val1, val2)
Examples
${gte(2, 3)}
false
keyboard_arrow_rightkeyboard_arrow_downif()
Evaluates the given condition and executes trueExpression or falseExpression depending on the evaluation result. This method is often used in HTML attributes, for example to conditionally enable / disable CSS classes etc. To do this, you can enter a value of null
in either trueExpression or falseExpression.
The is()
function is a shortcut for if(condition, trueExpression, null)
.
Usage
if(condition, trueExpression, falseExpression)
Notes
Only available in StructrScript because there is a native construct in JavaScript
Examples
${if(me.isAdmin, 'You have admin rights.', 'You do not have admin rights.')}
You have admin rights.
keyboard_arrow_rightkeyboard_arrow_downis()
Evaluates the given condition and executes trueExpression if the evaluation result is true. If the expression evaluates to false, NULL is returned. This method is often used in HTML attributes, for example to conditionally select, check, disable form elements.
If used in other scripting contexts and the result is used further, a construct using if()
is probably a better choice.
Usage
is(condition, trueExpression)
Notes
Only available in StructrScript because there is a native construct in JavaScript
Examples
${is(equal(this.name, request.name), 'selected')}
'selected' (if the name of the current object and the requested name are equal)
keyboard_arrow_rightkeyboard_arrow_downlt()
Returns a boolean value that indicates whether the numerical value val1 is smaller than the numerical value val2. This method tries to convert its parameter objects into numerical values, i.e. you can compare strings numerically.
Usage
lt(val1, val2)
Examples
${lt(1, 2)}
${lt(now, now)}
${lt(now, date_add(now, 1))}
true
false
true
keyboard_arrow_rightkeyboard_arrow_downlte()
Returns a boolean value that indicates whether the numerical value val1 is smaller or equal than the numerical value val2. This method tries to convert its parameter objects into numerical values, i.e. you can compare strings numerically.
Usage
lte(val1, val2)
Examples
${lte(2, 2)}
true
keyboard_arrow_rightkeyboard_arrow_downnot()
Returns the logical negation of the given boolean argument.
Usage
not(boolean)
Examples
${not(true)}
false
keyboard_arrow_rightkeyboard_arrow_downor()
Returns the logical OR result of the given boolean values.
Usage
or(boolean1, boolean2, ...)
Examples
${or(true, false)}
true
Collection Functions
keyboard_arrow_rightkeyboard_arrow_downall()
Evaluates a StructrScript expression for every element of a collection and returns true
if the expression evaluates to true
for all of the elements. The keyword data
contains a reference to the loop variable. See also: any()
and none()
.
Usage
all(collection, expression)
Notes
Only available in StructrScript because there is a native construct in JavaScript
Examples
${all(user.groups, is_allowed(data, current, 'read'))}
${all(merge(6, 7, 8, 12, 15), gt(data, 10))}
${all(merge(6, 7, 8, 12, 15), gt(data, 4))}
true (if all of the users groups are allowed to read the 'current' object)
false
true
keyboard_arrow_rightkeyboard_arrow_downany()
Evaluates a StructrScript expression for every element of a collection and returns true
if the expression evaluates to true
for any of the elements. The keyword data
contains a reference to the loop variable.. See also: all()
and none()
.
Usage
any(collection, expression)
Notes
Only available in StructrScript because there is a native construct in JavaScript
Examples
${any(merge(6, 7, 8, 12, 15), gt(data, 10))}
${any(merge(6, 7, 8, 12, 15), gt(data, 20))}
${any(me.groups, is_allowed(data, current, 'read'))}
${any(find('User', me.id).groups, is_allowed(data, current, 'read'))}
${any(get(find('User', me.id), 'groups'), is_allowed(data, current, 'read'))}
true
false
true (if any of the users groups are allowed to read the 'current' object)
will result in an error because the dot-notation does not take precedence over the parameter parsing. The next example shows how it can be done
true (if any of the users groups are allowed to read the 'current' object)
keyboard_arrow_rightkeyboard_arrow_downcomplement()
Returns the result of removing the removeObjects
from sourceList
.
Usage
complement(sourceList, removeObjects...)
Notes
If an object in the list of
removeObject
s is a list, all elements of these lists are removed from thesourceList
. (see example 3)If an object occurrs multiple times in the
sourceList
and is not removed, it will remain multiple times in the returned list. (see example 4)
Examples
(1) ${complement(merge(3, 4, 2, 1, 5, 6), 5, 1, 3)}
(2) ${complement(merge(1, 2, 7, 4, 5, 6, 7, 8, 9), 1, merge(9, 7, 5), 3, merge(4, 6))}
(3) ${complement(merge(1, 2, 1), 1)}
(4) ${complement(merge(1, 2, 1), 2)}
(1) [4.0, 2.0, 6.0]
(2) [2.0, 8.0]
(3) [2.0]
(4) [1.0, 1.0]
keyboard_arrow_rightkeyboard_arrow_downdouble_sum()
Returns the sum of all the values in the given collection as a floating-point value. This method will most likely be used in combination with the extract()
or merge()
functions.
Usage
double_sum(collection)
Examples
${double_sum(merge(1, 2, 3, 4))}
${double_sum(extract(find('Product'), 'itemPrice'))}
10.0
keyboard_arrow_rightkeyboard_arrow_downeach()
Executes the given expression for each element in the given collection. The individual objects of the collection are passed into the filter expression sequentially, using the data key data
. This method returns no content.
Usage
each(collection, eachExpression)
Notes
The collection can also be a
String[]
(see example 2)Only available in StructrScript because there are multiple native constructs in JavaScript (
for
,forEach
,for of
,for in
)
Examples
(1) ${each(find('User'), print(data.name))}
(2) ${each(get(first(find('User')), 'sessionIds'), print(data))}
(1) adminuser1user2user3
(2) all sessionIds for the first found user
keyboard_arrow_rightkeyboard_arrow_downextract()
This method iterates over the contents of the given entity collection and extracts the value for the given property key of each element. The return value of this method is a collection of extracted property values. It is often used in combination with find()
and join()
to create comma-separated lists of entity values.
Usage
extract(collection, propertyKey)
Examples
${extract(find('User'), 'name')}
[admin, user1, user2, user3]
keyboard_arrow_rightkeyboard_arrow_downfilter()
Filters the given collection according to the given filter expression, returning a subset of the original collection. The filter expression can be any valid expression that returns a boolean value. This method can be used to remove single or multiple elements from an existing list of objects. The individual objects of the collection are passed into the filter expression sequentially, using the data key data
.
The function will remove any object from the collection for which the filter expression returns false.
Usage
filter(collection, filterExpression)
Notes
Only available in StructrScript because there is a native construct in JavaScript
Array.prototype.filter()
.
Examples
${filter(find('User'), not(equal(data.name, 'admin')))}
unfiltered: [admin, user1, user2, user3]
filtered: [user1, user2, user3]
keyboard_arrow_rightkeyboard_arrow_downfirst()
Returns the first element from the given collection. This method is often used in conjunction with find()
to return the first result of a query.
Usage
first(collection)
Examples
${first(find('User'))}
f02e59a47dc9492da3e6cb7fb6b3ac25
keyboard_arrow_rightkeyboard_arrow_downint_sum()
Returns the sum of all the values in the given collection as an integer value. This method will most likely be used in combination with the extract()
or merge()
functions.
Usage
int_sum(collection)
Examples
${int_sum(merge(1, 2, 3, 4))}
10
keyboard_arrow_rightkeyboard_arrow_downis_collection()
Returns a boolean value that indicates whether the given object is a collection.
Usage
is_collection(obj)
Examples
${is_collection(find('User'))}
true
keyboard_arrow_rightkeyboard_arrow_downkeys()
Returns the list of property keys for the given entity or object in the given property view. Or, when used with a single parameter that is a map / non-entity object type: returns all the keys for which values are set in the given object.
Usage
keys(entity, propertyView)
keys(object)
Examples
${keys(page, 'public')}
[id, type, path, children, linkingElements, contentType, owner, cacheForSeconds, version, showOnErrorCodes, isPage, site, dontCache, pageCreatesRawData, enableBasicAuth, basicAuthRealm]
keyboard_arrow_rightkeyboard_arrow_downlast()
Returns the last element from the given collection. This method is often used in conjunction with find()
. See also first()
.
Usage
last(collection)
Examples
${last(find('User'))}
f02e59a47dc9492da3e6cb7fb6b3ac25
keyboard_arrow_rightkeyboard_arrow_downmerge()
Merges collections and objects into a single collection. This method can be used to add entities to a collection, or to merge multiple collections into a single one. All objects that are passed to this function will be added to the resulting collection. If a parameter is a collection, all objects of that collection are added to the resulting collection as well.
This method will not remove duplicate entries. Use merge_unique()
for that.
Usage
merge(object...)
Examples
${merge(1, 2, 3, 4, merge(3, 4, 5, 6))}
[1.0, 2.0, 3.0, 4.0, 3.0, 4.0, 5.0, 6.0]
keyboard_arrow_rightkeyboard_arrow_downmerge_unique()
Merges collections and objects into a single collection, removing duplicates. This method is very similar to merge()
except that the resulting collection will not contain duplicate entries.
Usage
merge_unique(object...)
Examples
${merge_unique(1, 2, 3, 4, merge(3, 4, 5, 6))}
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
keyboard_arrow_rightkeyboard_arrow_downnone()
Evaluates a StructrScript expression for every element of a collection and returns true
if the expression evaluates to true
for none of the elements. The keyword data
contains a reference to the loop variable.
See also: any()
and all()
.
Usage
none(collection, expression)
Notes
Only available in StructrScript because there is a native construct in JavaScript
Examples
${none(user.groups, is_allowed(data, current, 'read'))}
${none(merge(6, 7, 8, 12, 15), gt(data, 10))}
${none(merge(6, 7, 8, 12, 15), gt(data, 20))}
true (if none of the users groups are allowed to read the 'current' object)
false
true
keyboard_arrow_rightkeyboard_arrow_downnth()
Returns the element with the given index from the given collection. This method is often used in conjunction with find()
to return an element of the result list. See also find()
, first()
and last()
.
Usage
nth(collection, index)
Notes
The index is zero-based
Examples
${nth(find('User'), 2)}
${nth(merge('a', 'b', 'c'), 0)}
${nth(merge('a', 'b', 'c'), 2)}
f02e59a47dc9492da3e6cb7fb6b3ac25
a
c
keyboard_arrow_rightkeyboard_arrow_downsize()
Returns the size of the given collection.
Usage
size(collection)
Examples
${size(page.children)}
${size(merge('a', 'b', 'c'))}
${{ return $.size([1, 2, 3, 5, 8]); }}
1
3
5
keyboard_arrow_rightkeyboard_arrow_downslice()
IMPORTANT: The slice function has been removed with version 3.5 in favor of the advanced find access pattern.
This method returns elements from the given collection, list or array, starting at the given start argument, and ends at the given end argument.
If a queryFunction i used (i.e. find()
or search
) the start and end index are inserted into the cypher statement as LIMIT and SKIP parameters.
Usage
slice(queryFunction, start, end)
Notes
The JavaScript implementation of
slice()
works slightly differently from the StructrScript implementation. The JavaScript version only allows the queryFunction version from StructrScript. For regular JavaScript arrays you can use JavaScriptsArray.slice
function. Every queryFunction (i.e.find()
andsearch()
) inside the function will be sliced analogous to the StructrScript version.slice(queryFunction, start, end)
is intended to be used in conjunction with thebatch()
function in batched maintenance processes and therefor only available for privileged users. The slice start/end are simply ignored for non-admin users - there is no need to rewrite code.
Examples
(1) ${slice(merge("a", "b", "c", "d"), 1, 2)}
(2) ${slice(find('User'), 0, 10)}
(3) ${slice(find('User'), 0, request.count)}
(4)
${{
var retVal = Structr.slice(function() {
var users = Structr.find('User');
var files = Structr.find('File');
return {
f: files,
u: users
}
}, 0, 2);
Structr.print(retVal.f);
Structr.print(retVal.u);
}}
(1) "b"
(2) The first 10 users
(3) The first request.count users
(4) Would print the first 2 files and the first 2 users.
keyboard_arrow_rightkeyboard_arrow_downsort()
Sorts the given collection according to the given property key and returns the result in a new collection. The optional parameter sortDescending
is a boolean flag that indicates whether the sort order is ascending (default) or descending. This method is often used in conjunction with find()
.
The sort()
and find()
functions are often used in repeater elements in a function query, see Repeater Elements.
Parameters
Name | Type | Description |
---|---|---|
collection | Collection | The collection to be sorted |
propertyKey | String | The name of the property |
sortDescending | Boolean | Sort descending, if true. (optional) (default: false) |
Usage
sort(collection, propertyKey[, sortDescending = false])
Examples
${extract(sort(find('User'), 'name'), 'name')}
${extract(sort(find('User'), 'name', true), 'name')}
[admin, tester, user1, user2, user3]
[user3, user2, user1, tester, admin]
keyboard_arrow_rightkeyboard_arrow_downunwind()
Combines the given nested collections into to a single, “flat” collection. This method is the reverse of extract()
and can be used to flatten collections of related nodes that were created with nested extract()
calls etc. It is often used in conjunction with the find()
method like in the example below.
Usage
unwind(collections...)
Notes
unwind()
is quite similar tomerge()
. The big difference is thatunwind()
filters out empty collections.
Examples
${unwind(extract(find('Group'), 'members'))}
without unwind: [[b29e98329fb949b798162b88864aa038, 1224b74c018e4adf9cd6f5c07393f369, 6608098072bd44f68c0a9fdaa2571417]]
with unwind: [b29e98329fb949b798162b88864aa038, 1224b74c018e4adf9cd6f5c07393f369, 6608098072bd44f68c0a9fdaa2571417]
keyboard_arrow_rightkeyboard_arrow_downvalues()
Returns the list of property values for the given entity or object in the given property view. Or, when used with a single parameter that is a map / non-entity object type: returns all the values in the given object.
Usage
values(entity, propertyView)
values(object)
Examples
${values(page, 'public')}
Access Control Functions
These functions can be used to set access rights for users/groups to nodes. (see Node-level security)
keyboard_arrow_rightkeyboard_arrow_downadd_to_group()
Adds the given user as a member of the given group.
Usage
add_to_group(group, principal)
Examples
${add_to_group(first(find('Group', 'name', 'Admins')), me)}
keyboard_arrow_rightkeyboard_arrow_downcopy_permissions()
Copies the security configuration of an entity to another entity. If the overwrite
parameter is set to true, existing security relationships are overwritten. If it is not set (or omitted) the function works additively.
Usage
copy_permissions(sourceNode, targetNode[, overwrite = false])
Notes
If the target node has grants that the source node does not have, they are never changed
keyboard_arrow_rightkeyboard_arrow_downgrant()
Grants the given permissions on the given node to the given principal. This method creates or modifies the security relationship between the first two parameters. Valid values for the permission list are read
, write
, delete
and accessControl
. The permissions are passed in as a comma-separated list (see the examples below). The return value is the empty string. See also revoke()
and is_allowed()
.
Usage
grant(principal, node, permissions)
Examples
${grant(me, node1, 'read')}
${grant(me, node2, 'read, write')}
${grant(me, node3, 'read, write, delete')}
${grant(me, node4, 'read, write, delete, accessControl')}
keyboard_arrow_rightkeyboard_arrow_downis_allowed()
Returns a boolean value indicating the presence of the given permissions on the given node for the given principal. Valid values for the permission list are read
, write
, delete
and accessControl
. The permissions are passed in as a comma-separated list (see the examples below). See also grant()
and revoke()
.
Usage
is_allowed(principal, node, permissions)
Examples
${is_allowed(me, group1, 'read')}
${is_allowed(me, group2, 'write')}
${is_allowed(me, group2, 'read, write')}
${is_allowed(me, group2, 'read, write, delete')}
keyboard_arrow_rightkeyboard_arrow_downis_in_group()
Predicate function that returns if a given user is member of a given group.
New in v3.6: The optional parameter checkHierarchy
allows to check for indirect group membership. If the given principal is member of another group which is member of the given group the result will be true.
Usage
is_in_group(group, principal [ , checkHierarchy = false ])
Examples
${is_in_group(first(find('Group', 'name', 'Admins')), me)}
keyboard_arrow_rightkeyboard_arrow_downremove_from_group()
Removes the given user as a member of the given group.
Usage
remove_from_group(group, principal)
Examples
${remove_from_group(first(find('Group', 'name', 'Admins')), me)}
keyboard_arrow_rightkeyboard_arrow_downrevoke()
Revokes the given permissions on the given node from the given principal. This method modifies the security relationship between the first two parameters. Valid values for the permission list are read
, write
, delete
and accessControl
. The permissions are passed in as a comma-separated list (see the examples below). The return value is the empty string. See also grant()
and is_allowed()
.
Usage
revoke(principal, node, permissions)
Examples
${revoke(me, group1, 'read')}
${revoke(me, group2, 'read, write')}
${revoke(me, group2, 'read, write, delete')}
${revoke(me, group2, 'read, write, delete, accessControl')}
Entity Functions
keyboard_arrow_rightkeyboard_arrow_downcall()
Calls the SchemaMethod
with the given name and returns the result. This method is used to execute global schema methods (methods that are not associated with a type).
Usage
call(name [, key1, value1 [, ... ]] )
$.call(name [, map])
Notes
The method can only be executed if it is visible in the user context it is call()’ed in. This is analogous to calling global schema methods via REST.
Useful in situations where different types have the same or similar functionality but no common base class so the method can not be attached there
In a StructrScript environment parameters are passed as pairs of
'key1', 'value1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
Examples
${call('methodName', 'param1', 'value1', 'param2', 'value2')}
${{
$.call('methodName', {
param1: 'value1',
param2: 'value2'
})
}}
keyboard_arrow_rightkeyboard_arrow_downcall_privileged()
Calls the SchemaMethod
with the given name and returns the result. This method is used to execute global schema methods (methods that are not associated with a type).
Usage
call_privileged(name [, key1, value1 [, ... ]] )
$.call_privileged(name [, map])
Notes
Useful in situations where different types have the same or similar functionality but no common base class so the method can not be attached there
In a StructrScript environment parameters are passed as pairs of
'key1', 'value1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
Examples
${call_privileged('methodName', 'param1', 'value1', 'param2', 'value2')}
${{
$.call_privileged('methodName', {
param1: 'value1',
param2: 'value2'
})
}}
keyboard_arrow_rightkeyboard_arrow_downchangelog()
Returns the changelog for a specific entity. See Changelog for details on what the contents of a changelog are.
The resolve
parameter controls if remote entities are resolved. Every changelog entry which has a target
will be resolved as targetObj
(if the remote entity still exists in the database).
Filtering (supported from version 2.2)
All filter options are chained using the boolean AND operator. Only changelog entries matching all of the specified filters will be returned.
For filter keys which can occurr more than once, the filter values are combined using the boolean OR operator (see examples 1 and 2)
Filter Key | Applicable Changlog verbs (*) | Changelog Entry will be returned if | max. occurrences |
---|---|---|---|
timeFrom (**) | create, delete, link, unlink, change | timeFrom <= time of the entry | 1 (***) |
timeTo (**) | create, delete, link, unlink, change | timeTo >= time of the entry | 1 (***) |
verb | create, delete, link, unlink, change | verb of the entry matches at least one of the verbs | n (****) |
userId | create, delete, link, unlink, change | userId of the entry matches at least one of the userIds | n (****) |
userName | create, delete, link, unlink, change | userName of the entry matches at least one of the userNames | n (****) |
relType | link, unlink | rel of the entry matches at least one of the relTypes | n (****) |
relDir | link, unlink | relDir of the entry matches the given relDir | 1 (***) |
target | create, delete, link, unlink | target of the entry matches at least one of the targets | n (****) |
key | change | key of the entry matches at least one of the keys | n (****) |
(*) If a filter parameter is supplied, only changelog entries can be returned to which it is applicable. (e.g. combining key
and relType
can never yield a result as they are mutually exclusive)
(**) timeFrom/timeTo can be specified as a Long (time in ms since epoch), as a JavaScript Date object, or as a String with the format yyyy-MM-dd'T'HH:mm:ssZ
(***) The last supplied parameter takes precedence over the others
(****) The way we supply multiple occurrences of a keyword can differ from StructrScript to JavaScript
Usage
changelog(entity [, resolve=false [, filterKey1, filterValue2 [ , ... ] ] ] )
$.changelog(entity [, resolve=false [, map]])
Notes
The Changelog has to be enabled for this function to work properly. This can be done via the
application.changelog.enabled
key in configuration file structr.confThe
prev
andval
keys in thechange
event contain JSON encoded elements since they can be strings or arrays.In a StructrScript environment parameters are passed as pairs of
'filterKey1', 'filterValue1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
Examples
1. StructrScript
1. Return all changelog entries with verb=link
- `changelog(node, false, 'verb', 'link')`
2. Return all changelog entries with verb=(link OR unlink)
- `changelog(node, false, 'verb', 'link', 'verb', 'unlink')`
3. Return all changelog entries with (rel=OWNS) AND (verb=(link OR unlink))
- `changelog(node, false, 'verb', 'link', 'verb', 'unlink', 'relType', 'OWNS')`
- **Note**: filtering for the verbs link and unlink is redundant in this case as relType implies that only those verbs can be returned
4. Return all changelog entries with (target=<NODEID>) AND (verb=(link OR unlink))
- `changelog(node, false, 'verb', 'link', 'verb', 'unlink', 'target', '<NODEID>')`
- **Note**: In this case the verb filter makes sense as the fitler key `target` also applies to the verbs create and delete
2. The same examples in JavaScript. For each entry both versions are identical. One uses the StructrScript way of supplying parameters, the other uses the JavaScript way.
1. Return all changelog entries with verb=link
- `Structr.changelog(node, false, 'verb', 'link')`
- `Structr.changelog(node, false, {verb: 'link'});`
2. Return all changelog entries with verb=(link OR unlink)
- `Structr.changelog(node, false, 'verb', 'link', 'verb', 'unlink')`
- `Structr.changelog(node, false, {verb: ['link', 'unlink']});`
3. Return all changelog entries with (rel=OWNS) AND (verb=(link OR unlink))
- `Structr.changelog(node, false, 'verb', 'link', 'verb', 'unlink', 'relType', 'OWNS')`
- `Structr.changelog(node, false, {verb: ['link', 'unlink'], 'relType': 'OWNS'});`
4. Return all changelog entries with (target=<NODEID>) AND (verb=(link OR unlink))
- `Structr.changelog(node, false, 'verb', 'link', 'verb', 'unlink', 'target', '<NODEID>')`
- `Structr.changelog(node, false, {verb: ['link', 'unlink'], 'target': '<NODEID>'});`
keyboard_arrow_rightkeyboard_arrow_downcreate()
Creates a new node of the given type with the given value(s) for the given key(s). This method can be used with multiple key-value pairs. The return value is the newly created entity. See also delete()
.
Usage
create(type [, key1, value1 , ... ])
$(type [, map ]);
Notes
In a StructrScript environment parameters are passed as pairs of
'key1', 'value1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
Examples
${create('User', 'name', 'tester3')}
ab6fcef53dd24793bfa67754f414c61e
keyboard_arrow_rightkeyboard_arrow_downcreate_or_update()
Creates an object with the given properties or updates an existing object if it could be identified by a unique property. This function is a shortcut for a code sequence with a query that looks up an existing object and and a set() operation it if an object was found, or creates a new object with the given properties, if no object was found.
Usage
create_or_update(type, properties)
Notes
In a StructrScript environment parameters are passed as pairs of
'key1', 'value1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
Examples
${create_or_update("User", "eMail", "tester@test.com", "name", "New Name")}
If no object with the given e-mail address exists, a new object is created, because "eMail" is unique.
Otherwise, the existing object is updated with the new name.
keyboard_arrow_rightkeyboard_arrow_downcreate_relationship()
Creates a relationship of the given type between the two nodes. Please note that the inverse operation of this function is delete()
since it can be used to delete both nodes and relationships. This method returns the created relationship.
Usage
create_relationship(from, to, type [, key1, value1 [, ... ]] )
$.create_relationship(from, to, type [, map ]);
Notes
In a StructrScript environment parameters are passed as pairs of
'key1', 'value1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the fourth parameter.
Examples
${create_relationship(me, group, 'HAS')}
4793bfa4c61e67ab6fcef53dd2754f41
keyboard_arrow_rightkeyboard_arrow_downdelete()
Deletes the given node(s) or relationship(s). This method takes multiple parameters (or a collection of objects) and returns an empty string. See also create()
.
Usage
delete(entity, ...)
Examples
(1) ${delete(first(find('Project')))}
(2) ${delete(find('Project'))}
(1) deletes the first project
(2) deletes all projects
keyboard_arrow_rightkeyboard_arrow_downget()
Returns the value for the given property key from the given entity. This method will print an error message if the first parameter is null / not accessible. See get_or_null()
for a more tolerant get method.
Usage
get(entity, propertyKey)
Notes
The result value of the get() method can differ from the result value of property access using the dot notation (
get(this, 'name')
vsthis.name
) for certain property types (e.g. date properties), because get() converts the property value to its output representation. That means that a Date object will be formatted into a string when fetched viaget(this, 'date')
, whereasthis.date
will return an actual date object.
Examples
${get(page, 'name')}
my-page-name
keyboard_arrow_rightkeyboard_arrow_downget_incoming_relationships()
Returns all incoming relationships between the given nodes, with an optional qualifying relationship type.
Usage
get_incoming_relationships(from, to [, relType ])
Examples
${get_incoming_relationships(page, me)}
[org.structr.web.entity.relation.PageLink@548b, org.structr.core.entity.relation.PrincipalOwnsNode@5820]
keyboard_arrow_rightkeyboard_arrow_downget_or_null()
Returns the value for the given property key from the given entity, but doesn’t print an error message when the given entity is not accessible. See get()
for the equivalent method that prints an error if the first argument is null.
Usage
get_or_null(entity, propertyKey)
Examples
${get_or_null(page, 'name')}
my-page-name
keyboard_arrow_rightkeyboard_arrow_downget_outgoing_relationships()
Returns all outgoing relationships between the given nodes, with an optional qualifying relationship type.
Usage
get_outgoing_relationships(from, to [, relType ])
Examples
${get_outgoing_relationships(me, page)}
[org.structr.web.entity.relation.PageLink@548b, org.structr.core.entity.relation.PrincipalOwnsNode@5820]
keyboard_arrow_rightkeyboard_arrow_downget_relationship_types()
Returns the list of available relationship types form and/or to this node. Either potentially available (as defined in the schema) or actually available (existing relationships in the database).
Usage
get_relationship_types(node [, lookupType = 'existing' [, direction = 'both' ]])
Notes
node
: The node for which possible relationship types should be checkedlookupType
: Eitherexisting
orschema
direction
: Eitherincoming
,outgoing
orboth
Examples
${get_relationship_types(me, 'schema')}
${get_relationship_types(me, 'schema', 'incoming')}
${get_relationship_types(me, 'schema', 'outgoing')}
${get_relationship_types(me, 'existing')}
${get_relationship_types(me, 'existing', 'incoming')}
${get_relationship_types(me, 'existing', 'outgoing')}
[HOME_DIR, WORKING_DIR, OWNS, SECURITY, PICTURE_OF, FAVORITE, CONTAINS]
[OWNS, SECURITY, PICTURE_OF, CONTAINS]
[HOME_DIR, WORKING_DIR, OWNS, SECURITY, FAVORITE]
[OWNS, SECURITY, CONTAINS] (user owns nodes, has permissions on nodes and is contained in a group)
[OWNS, SECURITY] (user owns nodes and has permissions on nodes)
[CONTAINS] (user is contained in a group)
keyboard_arrow_rightkeyboard_arrow_downget_relationships()
Returns all relationships between the given nodes, with an optional qualifying relationship type.
Usage
get_relationships(from, to [, relType ])
Examples
${get_relationships(me, page)}
[org.structr.web.entity.relation.PageLink@548b, org.structr.core.entity.relation.PrincipalOwnsNode@5820]
keyboard_arrow_rightkeyboard_arrow_downhas_incoming_relationship()
Returns a boolean value indicating whether at least one incoming relationship exists between the given nodes, with an optional qualifying relationship type. See also incoming()
, outgoing()
, has_relationship()
and has_outgoing_relationship()
.
Usage
has_incoming_relationship(from, to [, relType ])
Examples
${has_incoming_relationship(me, page, 'OWNS')}
false
keyboard_arrow_rightkeyboard_arrow_downhas_outgoing_relationship()
Returns a boolean value indicating whether at least one outgoing relationship exists between the given nodes, with an optional qualifying relationship type. See also incoming()
, outgoing()
, has_relationship()
and has_incoming_relationship()
.
Usage
has_outgoing_relationship(from, to [, relType ])
Examples
${has_outgoing_relationship(me, page, 'OWNS')}
false
keyboard_arrow_rightkeyboard_arrow_downhas_relationship()
Returns a boolean value indicating whether at least one relationship exists between the given nodes, with an optional qualifying relationship type. See also incoming()
and outgoing()
.
Usage
has_relationship(node1, node2 [, relType ])
Examples
${has_relationship(me, page, 'OWNS')}
false
keyboard_arrow_rightkeyboard_arrow_downincoming()
Returns all incoming relationships, with an optional qualifying relationship type. This method can for example be used in the Function Query section of a Repeater Element to access the relationships of a node. See also outgoing()
and has_relationship()
.
Usage
incoming(node [, relType ])
Examples
${incoming(page)}
[org.structr.web.entity.relation.PageLink@548b, org.structr.web.entity.relation.PageLink@5820]
keyboard_arrow_rightkeyboard_arrow_downinstantiate()
Instantiates the given Neo4j node into a Structr node. This method can be used to convert raw Neo4j nodes obtained from a partial or mapped cypher()
result into Structr nodes.
Usage
instantiate(neo4jNode)
Examples
${instantiate(rawNode)}
a567cfb1e66249a095097493f764b464
keyboard_arrow_rightkeyboard_arrow_downis_entity()
Returns a boolean value that indicates whether the given object is a Structr entity (i.e. a node or relationship).
Usage
is_entity(obj)
Examples
${is_entity(me)}
true
keyboard_arrow_rightkeyboard_arrow_downmerge_properties()
Copies the values for the given list of property keys from the source entity to the target entity.
Usage
merge_properties(source, target, propertyKeys...)
Examples
${merge_properties(this, copy, 'name', 'content', 'version'}
keyboard_arrow_rightkeyboard_arrow_downoutgoing()
Returns all outgoing relationships, with an optional qualifying relationship type. This method can for example be used in the Function Query section of a Repeater Element to access the relationships of a node. See also incoming()
and has_relationship()
.
Usage
outgoing(node [, relType ])
Examples
${outgoing(me, 'OWNS')}
[org.structr.core.entity.relationship.PrincipalOwnsNode@5977, org.structr.core.entity.relationship.PrincipalOwnsNode@596f, org.structr.core.entity.relationship.PrincipalOwnsNode@5921]
keyboard_arrow_rightkeyboard_arrow_downset()
Sets the passed values for the given property keys on the specified entity, using the security context of the current user.
set()
accepts several different parameter combinations, where the first parameter is always a graph object. The second parameter can either be a list of (key, value) pairs, a JSON-coded string (to accept return values of the geocode()
function) or a map (e.g. a result from nested function calls or a simple map built in serverside JavaScript).
Usage
set(entity [, key1, value1, ... ])
set(entity, json)
set(entity, map)
Notes
In a StructrScript environment parameters are passed as pairs of
'key1', 'value1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the fourth parameter.
When using the
set()
method on an entity that is not writable by the current user, a 403 Forbidden HTTP error will be thrown. In this case, useset_privileged()
which will execute theset()
operation with elevated privileges.
Examples
// Key-Value examples
${set(user, 'name', 'new-user-name', 'eMail', 'new@email.com')}
${set(page, 'name', 'my-page-name')}
// JSON examples
${set(this, geocode(this.street, this.city, this.country))}
${set(me, "{name: 'new-user-name', age: 42, eMail: 'new@email.com'}")}
// JavaScript example
${{
let me = $.me;
$.set(me, {name: 'my-new-name', eMail: 'new@email.com'});
}}
keyboard_arrow_rightkeyboard_arrow_downset_privileged()
Sets the value for the given property key on the given entity to the given value, using admin permissions.
Usage
set_privileged(entity [, key1, value1, ... ])
set_privileged(entity, json)
set_privileged(entity, map)
Notes
In a StructrScript environment parameters are passed as pairs of
'key1', 'value1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the fourth parameter.
Examples
${set_privileged(page, 'accessCount', '2')}
keyboard_arrow_rightkeyboard_arrow_downto_csv()
Returns a CSV string representation of the given collection of objects.
Parameter | Description |
---|---|
nodes | A collection of objects (these objects can be database nodes or javascript objects) |
propertiesOrView | The name of a view (e.g. ui or public) or a collection of property names (e.g. merge(‘id’, ‘name’) in StructrScript or [‘id’, ‘name’] in JavaScript). If the nodes parameter was a collection of javascript objects this needs to be a collection of property names. If the nodes parameter was a collection of database nodes, a collection of property names or a view name can be used. |
delimiterChar | A single character used as the column separator. (If more than one character is supplied, only the first character is used without raising an error) (default: ; ) |
quoteChar | A single character used as the quote character. (If more than one character is supplied, only the first character is used without raising an error) (default (" ) |
recordSeparator | The separator between the records (recommended usage is \n, \r or \r\n) (default: \n ) |
includeHeader | Switch indicating if a header row should be printed (default true ) |
localizeHeader | Switch indicating if the column names in the header should be localized (default: false ) |
headerLocalizationDomain | Optional header localization domain |
Usage
to_csv(nodes, propertiesOrView[, delimiterChar = ';' [, quoteChar = '"' [, recordSeparator = "\n" [, includeHeader = true[, localizeHeader = false [, headerLocalizationDomain]]]])
Notes
If the column values contain the quote character, a
\
is prepended before that instance of the quote characterAll instances of
\n
or\r
in the column values are replaced by\\n
and\\r
respectively so we can guarantee that only intended newlines (i.e. the record separator) occurr inside the produced CSVThe content of the header row depends on the contents of
propertiesOrView
and the localization configuration.If a view is given, the (optionally localized) property names of that view are used as header row
If a collection of properties is given, these (optionally localized) property names are used as a header row
Examples
${to_csv(find('User'), 'public')}
${to_csv(find('User'), merge('id', 'name'))}
"id";"type";"name";"isUser"
"70fd9f831cad4506a1076f956ffa2a0b";"User";"admin";"true"
"id";"name"
"70fd9f831cad4506a1076f956ffa2a0b";"admin"
keyboard_arrow_rightkeyboard_arrow_downto_excel()
Returns a XLSX string representation of the given collection of objects.
Parameter | Description |
---|---|
nodes | A collection of objects (these objects can be database nodes or javascript objects) |
propertiesOrView | The name of a view (e.g. ui or public) or a collection of property names (e.g. merge(‘id’, ‘name’) in StructrScript or [‘id’, ‘name’] in JavaScript). If the nodes parameter was a collection of javascript objects this needs to be a collection of property names. If the nodes parameter was a collection of database nodes, a collection of property names or a view name can be used. |
includeHeader | Switch indicating if a header row should be printed (default: true ) |
localizeHeader | Switch indicating if the column names in the header should be localized (default: false ) |
headerLocalizationDomain | Optional header localization domain |
maxCellLength | The maximum length (affects content-rows only - the header remains untouched) |
overflowMode | Controls how content that is longer than maxCellLength is handled (affects content-rows only - the header remains untouched)
Any other value is used as is as a cell comment. This is useful to display a message like “The content of this cell has been truncated” |
Usage
to_excel(nodes, propertiesOrView[, includeHeader = true[, localizeHeader = false [, headerLocalizationDomain[, maxCellLength = 32767 [, overflowMode = 'o']]]]])
Notes
The output of this function is a complete excel file, so the complete data must be contained in the
nodes
parameter and can not be appended later onThis function is intended to be used in conjunction with the
set_content()
function or in a dynamic fileIMPORTANT: The dynamic file should have the charset
ISO-8859-1
specified in itscontentType
(e.g.application/octet-stream; charset=ISO-8859-1
)The content of the header row depends on the contents of
propertiesOrView
and the localization configuration.If a view is given, the (optionally localized) property names of that view are used as header row
If a collection of properties is given, these (optionally localised) property names are used as a header row
IMPORTANT: If you are creating Excel document from a dynamic file, make sure that there are no extraneous whitespaces after the dynamic script content. This is very hard to find and Excel will warn the user that the created file is corrupt and has to be repaired!
Limitations
There are some inherent limits in the Excel file formats. Structr is creating
EXCEL2007
spreadsheets. The following limitations are taken directly from the documentation:Maximum length of text cell contents is 32767
Maximum length of text cell comments is 32767
The total number of available rows is 1M (2^20)
The total number of available columns is 16K (2^14)
The maximum number of arguments to a function is 255
Number of conditional format conditions on a cell is unlimited (actually limited by available memory in Excel)
Number of cell styles is 64000
Examples
1. Create a new file "new_document.xlsx" containing the list of users.
${set_content(create('File', 'name', 'new_document.xlsx'), to_excel(find('User'), 'public'), 'ISO-8859-1')}
2. Both of the following examples would results in a downloadable file named `user-export.xlsx` containing the list of users.
The scripts would need to be placed in a [dynamic file](438) with the charset `charset=ISO-8859-1` appended to the content-type.
${(
set_response_header('Content-Disposition', 'attachment; filename="user-export.xlsx"'),
to_excel(find('User'), 'public')
)}
${{
// JavaScript Example
$.setResponseHeader('Content-Disposition', 'attachment; filename="user-export.xlsx"');
$.print(Structr.toExcel(Structr.find('User'), 'public'));
}}
3. The following example would result in a downloadable file named `users-truncated.xlsx` where all cells are truncated after 1000 characters. The parameters concerning the header row configure that a header is printed which is not localized.
The scripts would need to be placed in a [dynamic file](438) with the charset `charset=ISO-8859-1` appended to the content-type.
${{
$.setResponseHeader('Content-Disposition', 'attachment; filename="users-truncated.xlsx"');
$.print(Structr.toExcel(Structr.find('User'), 'excelView', true, false, '', 1000, 't'));
}}
keyboard_arrow_rightkeyboard_arrow_downto_graph_object()
Tries to convert given object or collection containing graph objects into a graph object. If an element in the source can not be converted to a graph object, it is ignored. Graph objects can be used in repeaters for example and thus it can be useful to create custom graph objects for iteration in such contexts. The optional view
parameter can be used to select the view representation of the entity. If no view is given, the public
view is used. The optional depth
parameter defines at which depth the conversion stops. If no depth is given, the default value of 3 is used.
Usage
to_graph_object(source [, view = 'public' [, depth = 3]])
Notes
Since strings can not be converted to graph objects but it can be desirable to use collections of strings in repeaters (e.g. the return value of the
inheriting_types()
function), collections of strings are treated specially and converted to graph objects withvalue
=><string>
as its result. (see example 2)
Examples
(1)
${{
var coll = $.to_graph_object([
{id:"o1",name:"objectA"},
{id:"o2",name:"objectB"}
]);
$.print(coll.join(', '));
}}
(2)
${to_graph_object(inheriting_types('Principal'))}
(1) {id=o1, name=objectA}, {id=o2, name=objectB}
(2) [{value=Principal},{value=Group},{value=LDAPGroup},{value=LDAPUser},{value=User}]
keyboard_arrow_rightkeyboard_arrow_downto_json()
Returns a JSON string representation of the given object very similar to JSON.stringify()
in JavaScript. The output of this method will be very similar to the output of the REST server except for the response headers and the result container. The optional view
parameter can be used to select the view representation of the entity. If no view is given, the public
view is used. The optional depth
parameter defines at which depth the JSON serialization stops. If no depth is given, the default value of 3 is used.
Usage
to_json(source [, view = 'public' [, depth = 3]])
Notes
For database objects this method is preferrable to
JSON.stringify()
because a view can be chosen.JSON.stringify()
will only return theid
andtype
property for nodes.
Examples
${to_json(me)}
{ "id": "6608098072bd44f68c0a9fdaa2571417", "type": "User", "isUser": true, "name": "tester1" }
keyboard_arrow_rightkeyboard_arrow_downunlock_readonly_properties_once()
Allows temporary access to read-only properties. This method will cause a single following call to set()
on a read-only property to succeed. See also set_privileged()
.
Usage
unlock_readonly_properties_once(node)
keyboard_arrow_rightkeyboard_arrow_downunlock_system_properties_once()
Allows temporary access to system properties. This method will cause a single following call to set()
on a system property to succeed. See also set_privileged()
.
Usage
unlock_system_properties_once(node)
keyboard_arrow_rightkeyboard_arrow_downuser_changelog()
Returns the changelog for the changes a specific user made.
Usage
user_changelog(user [, resolve=false [, filterKey1, filterValue2 [ , ... ] ] ] )
$.user_changelog(user [, resolve=false [, map]])
Notes
Functionally identical to the changelog() function - only the data source is different.
The User changelog has to be enabled for this function to work properly. This can be done via the application.changelog.user_centric.enabled key in configuration file structr.conf
Geo Functions
keyboard_arrow_rightkeyboard_arrow_downgeocode()
Returns the geocoding result for the given parameters. See Geocoding Configuration for more information. This method returns a nested object with latitude / longitude that can directly be used in the set()
method.
Usage
geocode(street, city, country)
Examples
${set(this, geocode(this.street, this.city, this.country))}
keyboard_arrow_rightkeyboard_arrow_downimport_gpx()
Imports a GPX string and returns a complex object with its contents.
Usage
add(gpxString)
Examples
${ import_gpx( get_content( first(find('File', 'name', '20090815.gpx')) ) ) }
(Note: Indentation added for documentation purposes)
{
tracks = [
{
segments = [
{
points = [
{latitude=50.121096, longitude=8.641047, time=2009-08-15T08:37:23Z, altitude=168.3, horizontalDilution=3.2, verticalDilution=1.0, positionDilution=3.3},
{latitude=50.12099, longitude=8.639938, time=2009-08-15T08:37:37Z, altitude=168.3, horizontalDilution=3.2, verticalDilution=1.0, positionDilution=3.3}
]
}
]
}
]
}
keyboard_arrow_rightkeyboard_arrow_downlat_lon_to_utm()
Converts the given latitude/longitude coordinates into an UTM string.
Usage
lat_lon_to_utm(latitude, longitude)
Examples
${lat_lon_to_utm(53.85499997165232, 8.081674915658844)}
"32U 439596 5967780"
keyboard_arrow_rightkeyboard_arrow_downutm_to_lat_lon()
Converts the given UTM string into latitude/longitude coordinates.
Usage
utm_to_lat_lon(utmString)
Examples
${utm_to_lat_lon("32 N 439596 5967780")}
{latitude=53.85499997165232, longitude=8.081674915658844}
HTTP Functions
keyboard_arrow_rightkeyboard_arrow_downDELETE()
Sends an HTTP DELETE request with an optional content type to the given url. This method can be used to make HTTP requests from within the Structr Server, triggered by a frontend control like a button etc.
The DELETE()
method will return a response object with the following structure:
Field | Description | Type |
---|---|---|
status | HTTP status of the request | Integer |
headers | Response headers | Map |
body | Response body | Map or String |
Usage
DELETE(url [, contentType = 'application/json' ])
Notes
The
DELETE()
method will not be executed in the security context of the current user. The request will be made by the Structr server, without any user authentication or additional information. If you want to access external protected resources, you will need to authenticate the request usingadd_header()
.
Examples
${DELETE('http://localhost:8082/structr/rest/User/6aa10d68569d45beb384b42a1fc78c50')}
{body={code=401.0, message=Forbidden}, status=401, headers={Date=Tue, 22 Dec 2015 16:39:20 GMT, Content-Type=application/json; charset=utf-8, Content-Length=44, Server=Jetty(9.2.9.v20150224)}}
keyboard_arrow_rightkeyboard_arrow_downGET()
This method makes a server-side HTTP GET request to the given url and returns the literal HTTP response (without the headers - If you are interested in the response headers, use the HEAD()
function).
The contentType
only serves as way to handle certain formats differently:
- The value text/html
parses the returned text as HTML using JSOUP and allows for an optional third parameter selector
to select a subset of the HTML response, as documented in the JSOUP Cookbook.
- From version 3.5 onwards, GET() supports binary content by setting the contentType
parameter to application/octet-stream
. (This is helpful when creating files - see below example)
- Any other value for contentType
simply returns the literal HTTP response
Usage
GET(url [, contentType [, username, password]])
GET(url, 'text/html', selector)
GET(url, 'application/octet-stream' [, username, password]])
Notes
v4.0+:
contentType
can be used like theContent-Type
header - to set the expected response mime type and to set thecharset
with which the response will be interpreted (unless the server sends provides a charset, then this charset will be used)Prior to v4.0:
contentType
is the expected response content type (it does not influence the charset of the response - the charset from the sending server will be used)username
andpassword
are intended for HTTP Basic Auth. For header authentication useadd_header()
The
GET()
method will not be executed in the security context of the current user. The request will be made by the Structr server, without any user authentication or additional information. If you want to access external protected resources, you will need to authenticate the request usingadd_header()
. (see the related articles for more information)
Examples
(1) ${GET('http://localhost:8082/structr/rest/User')}
(2)
${
(
add_header('X-User', 'admin'),
add_header('X-Password', 'admin'),
GET('http://localhost:8082/structr/rest/User')
)
}
(3) ${GET('http://www.google.com', 'text/html')}
(3a) ${GET('http://www.google.com', 'text/html; charset=UTF-8')}
(3b) ${GET('http://www.google.com', 'text/html; charset=ISO-8859-1')}
(4) ${GET('http://www.google.com', 'text/html', '#footer')}
(5) ${set_content(create('File', 'name', 'google_logo.png'), GET('https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png', 'application/octet-stream'))}
(1) An "Access denied" message with code 401 from that structr instance (depending on the configuration of that instance)
(2) The list of users from that structr instance (depending on the configuration of that instance)
(3) The front page of google.com
(3a) The front page of google.com (since the server sends a charset in the response, the given charset parameter is overridden)
(3b) The front page of google.com (since the server sends a charset in the response, the given charset parameter is overridden)
(4) The HTML element with the ID 'footer' from google.com
(5) A new file with the google logo is created in the local structr instance
keyboard_arrow_rightkeyboard_arrow_downHEAD()
Sends an HTTP HEAD request to the given url. This method can be used to make HTTP requests from within the Structr Server, triggered by a frontend control like a button etc. The optional username and password parameters can be used to authenticate the request.
The HEAD()
method will return a response object with the following structure:
Field | Description | Type |
---|---|---|
status | HTTP status of the request | Integer |
headers | Response headers | Map |
Usage
HEAD(url [, username, password ])
Notes
The
HEAD()
method will not be executed in the security context of the current user. The request will be made by the Structr server, without any user authentication or additional information. If you want to access external protected resources, you will need to authenticate the request usingadd_header()
. (see the related articles for more information)
Examples
${HEAD('http://localhost:8082/structr/rest/User', 'tester', 'test')}
{status=401, headers={Date=Tue, 22 Dec 2015 16:53:30 GMT, Content-Type=application/json; charset=ISO-8859-1, Connection=close, Server=Jetty(9.2.9.v20150224)}}
keyboard_arrow_rightkeyboard_arrow_downPOST()
Send an HTTP POST request with the given body to the given url. This method can be used to make HTTP requests from within the Structr Server, triggered by a frontend control like a button etc.
The POST()
method will return a response object containing the reposonse headers, body and status code. The object has the following structure:
Field | Description | Type |
---|---|---|
status | HTTP status of the request | Integer |
headers | Response headers | Map |
body | Response body | Map or String |
Usage
POST(url, body [, contentType = 'application/json' [, charset = 'utf-8' ] ] )
Notes
contentType
is the expected response content type. If you need to define the request content type, useadd_header('Content-Type', 'your-content-type-here')
If the
contentType
isapplication/json
, the response body is automatically parsed and thebody
key of the returned object is a mapThe
POST()
method will not be executed in the security context of the current user. The request will be made by the Structr server, without any user authentication or additional information. If you want to access external protected resources, you will need to authenticate the request usingadd_header()
.
Examples
${POST('http://localhost:8082/structr/rest/User', '{name: "Tester"}')}
{body={code=401.0, message=Forbidden}, status=401, headers={Date=Tue, 22 Dec 2015 16:39:20 GMT, Content-Type=application/json; charset=utf-8, Content-Length=44, Server=Jetty(9.2.9.v20150224)}}
keyboard_arrow_rightkeyboard_arrow_downPUT()
Send an HTTP PUT request with the given body to the given url. This method can be used to make HTTP requests from within the Structr Server, triggered by a frontend control like a button etc.
The PUT()
method will return a response object with the following structure:
Field | Description | Type |
---|---|---|
status | HTTP status of the request | Integer |
headers | Response headers | Map |
body | Response body | Map or String |
Usage
PUT(url, body [, contentType = 'application/json' [, charset = 'utf-8' ]] )
Notes
contentType
is the expected response content type. If you need to define the request content type, useadd_header('Content-Type', 'your-content-type-here')
If the MIME type of the response is
application/json
, thebody
field will contain the mapped response as a Structr object that can be accessed using the dot notation (e.g.result.body.result_count
). Otherwise, the body field will contain the response as a string. (see the related articles for more information)The
PUT()
method will not be executed in the security context of the current user. The request will be made by the Structr server, without any user authentication or additional information. If you want to access external protected resources, you will need to authenticate the request usingadd_header()
.
Examples
${PUT('http://localhost:8082/structr/rest/User/6aa10d68569d45beb384b42a1fc78c50', '{"name": "Tester"}')}
{body={code=401.0, message=Forbidden}, status=401, headers={Date=Tue, 22 Dec 2015 16:39:20 GMT, Content-Type=application/json; charset=utf-8, Content-Length=44, Server=Jetty(9.2.9.v20150224)}}
keyboard_arrow_rightkeyboard_arrow_downadd_header()
Temporarily adds the given (key, value) tuple to the local list of request headers. All headers in this list will be added to any subsequent GET()
, HEAD()
, POST()
, PUT()
or DELETE()
call in the same request (meaning the request from the client to structr).
Usage
add_header(key, value)
Notes
Prior to 3.5.0 it was not possible to remove headers. In 3.5.0 this function was changed to remove a header if
value = null
was provided as an argument.
Examples
(1) StructrScript
${
(
add_header('X-User', 'tester1'),
add_header('X-Password', 'test'),
GET('http://localhost:8082/structr/rest/User')
)
}
(2) JavaScript
${{
$.add_header('X-User', 'tester1');
$.add_header('X-Password', 'test');
let result = $.GET('http://localhost:8082/structr/rest/User');
}}
{ "code": 401, "message": "Wrong username or password, or user is blocked. Check caps lock. Note: Username is case sensitive!" }
(Please note that this example deliberately uses the wrong credentials to provoke the above error message.)
keyboard_arrow_rightkeyboard_arrow_downclear_headers()
Removes all headers previously set with add_header()
in the same request.
Usage
clear_headers()
Notes
This is important if multiple calls to the family of HTTP functions is made in the same request to clear the headers in between usages to prevent sending superfluous headers in subsequent requests.
This function has been introduced in v4.0
keyboard_arrow_rightkeyboard_arrow_downget_request_header()
Returns the value of the HTTP request header with the given name. This method can be used both in Entity Callback Functions and in the Page Rendering process to obtain the value of a given HTTP header, allowing the user to use HTTP headers from their web application clients to control features of the application.
Usage
get_request_header(name)
Examples
${get_request_header('User-Agent')}
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:43.0) Gecko/20100101 Firefox/43.0
keyboard_arrow_rightkeyboard_arrow_downset_response_code()
Sets the response code of the current rendering run. Very useful in conjunction with set_response_header()
for redirects.
Usage
set_response_code(value)
Examples
${set_response_code(302)}
keyboard_arrow_rightkeyboard_arrow_downset_response_header()
Sets the value of the HTTP response header with the given name to the given value. This method can be used to set and/or override HTTP response headers in the Structr server implementation to control certain aspects of browser / client behaviour.
Usage
set_response_header(name, value)
set_response_header(name, value [, override]) // New in v.3.6
Notes
The following example will cause the browser to display a “Save as…” dialog when visiting the page, because the response content type is set to
text/csv
.
Examples
${set_response_header('Content-Type', 'text/csv')}
keyboard_arrow_rightkeyboard_arrow_downvalidate_certificates()
Enables or disables certificate validation for outgoing requests. All subsequent GET()
, HEAD()
, POST()
, PUT()
or DELETE()
calls in the same request (meaning the request from the client to structr) will use the setting configured here.
Usage
validate_certificates(true)
validate_certificates(false)
Notes
By default, certificate validation is always enabled - only in rare cases would/should it be necessary to change this behaviour.
This function was introduced in v4.2 and is not available before that
Examples
${{
$.validate_certificates(false);
let result = $.GET('https://www.domain-with-invalid-certificate.com/resource.json');
}}
I/O Functions
keyboard_arrow_rightkeyboard_arrow_downappend()
Appends a string representation of the given values to a file underneath the Structr exchange/
directory. See Anatomy of a Structr application for more information.
Usage
append(filepath, data...)
Notes
The
exchange/
directory itself may be a symbolic linkUnderneath the
exchange/
the canonical path of a file has to be identical to the provided filepath in order to prevent directory traversal attacksThis means that symbolic links inside the
exchange/
directory are forbiddenAlso path traversal is forbidden
Example 1: Allowed ‘sub/dir/file.txt’
Example 2: Forbidden ‘../../../../etc/passwd’
Example 3: Forbidden ‘/etc/passwd’
Examples
${append('info.txt', 'Hello, ', 'world!')}
${append('subdir/info.txt', 'Hello, ', 'world!')}
keyboard_arrow_rightkeyboard_arrow_downappend_content()
Appends the given content to the given file.
Usage
append_content(file, content[, encoding = "UTF-8"])
Notes
The
encoding
parameter is used when writing the data to the file. The default (UTF-8
) rarely needs to be changed but can be very useful when working with binary strings.
Examples
append_content(first(find('File', 'name', 'test.txt')), '\nAdditional Content')
keyboard_arrow_rightkeyboard_arrow_downcopy_file_contents()
Copies the content of sourceFile to targetFile and updates the meta-data accordingly.
Usage
copy_file_contents(sourceFile, targetFile)
keyboard_arrow_rightkeyboard_arrow_downcreate_archive()
Creates and returns a ZIP archive with the given file (and folder) nodes and saves that archive under the name given as the first parameter.
The third parameter CustomFileType
can be used if the schema defines a type inheriting from File
and we want the archive to be of that type.
Usage
create_archive(archiveFileName, files[, CustomFileType])
Notes
The
files
parameter can be a single file, a collection of files, a folder, a collection of folders or a mixture.The resulting file will be named
archiveFileName
+.zip
and will be put in the root folder of the structr filesystem.
Examples
${create_archive("logs", find("Folder", "name", "logs"))}
${{Structr.createArchive("logs", Structr.find("Folder", "name", "logs"))}}
keyboard_arrow_rightkeyboard_arrow_downcreate_zip()
Creates and returns a ZIP archive with the given name (first parameter), containing the given files/folders (second parameter).
By setting a password as the optional third parameters, the ZIP file will be encrypted.
If the optional fourth parameter is aes
or AES
, the ZIP file will be encrypted with the AES256 method.
Usage
create_zip(archiveFileName, files [, password [, encryptionMethod ] ])
Notes
The AES encryption method is not supported by the most operating system’s default unarchiving tools. You might need to install additional software like 7zip or Winzip in order to successfully unarchive and decrypt the ZIP files in case of using the AES method.
Examples
${create_zip('test_encrypted', merge(find('Folder', 'name', 'a'), find('Folder', 'name', 'b')), 'mySecretPassword', 'aes')}
keyboard_arrow_rightkeyboard_arrow_downdebug()
This function either behaves like a no-op or it behaves exactly like the log()
function. This depends on the configuration setting log.debug
.
Usage
debug(objects...)
keyboard_arrow_rightkeyboard_arrow_downexec()
Executes the script with the given name. In order to prevent execution of arbitrary code from the Structr rendering context, the script must be registered in structr.conf file using the following syntax.
key.for.my.script = my-script.sh
Upon successful execution, the exec()
call returns the output of the script.
Usage
exec(key [, parameters... ] )
Notes
All script files are looked up inside a
scripts
folder in the main folder.Symlinks are not allowed, director traversal is not allowed.
The key of the script must be all-lowercase.
This method does not preserve binary content, it can not be used to stream binary data through Structr. Use
exec_binary()
for that.
Examples
${exec('key.for.my.script')}
Hello from my-script.sh!
keyboard_arrow_rightkeyboard_arrow_downexec_binary()
This method is very similar to exec()
, but instead of returning the (text) result of the execution, it will copy its input stream to the given output buffer without modifying the binary data. This is important to allow streaming of binary data from a script to the client.
Usage
exec_binary(output, name, parameters...)
exec_binary(output, name)
Notes
All script files are looked up inside a
scripts
folder in the main folder.Symlinks are not allowed, director traversal is not allowed.
The key of the script must be all-lowercase.
Examples
${exec_binary(response, 'my.create.pdf')}
results in the streaming of the binary content of the `my.create.pdf` script to the client.
keyboard_arrow_rightkeyboard_arrow_downflow()
This method is used to execute a particular flow and returns the evaluation result of the Flow with the given effective name.
Usage
flow(effectiveName [, parameters... ])
flow(effectiveName [, parameterMap ])
Notes
The effective name which is the combined name of the flow plus all its parent packages.
Examples
$.flow('package1.flow1', {
'parameter1' : 42,
'parameter2' : 3.14
})
keyboard_arrow_rightkeyboard_arrow_downget_content()
Retrieves the content of the given file from the Structr filesystem. This method can be used to access the binary content of a file stored in Structr
Usage
get_content(file[, encoding = "UTF-8"])
Notes
The parameter
encoding
is available from version 2.3.9+
Examples
${get_content(first(find('File', 'name', 'test.txt')))}
keyboard_arrow_rightkeyboard_arrow_downlog()
Prints a string representation of the given objects to the Structr log file.
Usage
log(objects...)
Notes
Nodes are printed as
NodeType(name, uuid)
. If you want a JSON representation, you log the output ofto_json(node, view)
(if you useJSON.stringify
the default viewpublic
will be used)
Examples
${log('Hello, world')}
keyboard_arrow_rightkeyboard_arrow_downpdf()
Returns a PDF string representation of the given page.
Parameters
- page
: The page that should be rendered as a PDF
- wkhtmltopdfParameter
: This string is passed to wkhtmltopdf and may contain all parameters that wkhtmltopdf accepts
- a useful parameter is --disable-smart-shrinking
- baseUrl
: The baseUrl for the main page (the header and footer page need the baseUrl explicitly as they are currently provided as a string)
- defaults to the value of the keyword base_url
- runWithXServer
: Forces the usage of xvfb
- xServerSettings
: parameters for xvfb
Usage
pdf(page [, wkhtmltopdfParameter, baseUrl, runWithXServer, xServerSettings])
Notes
The PDF functionality relies on other software: wkhtmltopdf. This needs to be installed on the server. It is recommended to install a wkhtmltopdf release from github to ensure that a version with patched qt is installed. See the autogenerated documentation for wkhtmltopdf.
IMPORTANT: If you are creating a PDF document from a dynamic file, make sure that there are no extraneous whitespaces after the dynamic script content. This will lead to corrupt PDFs and is very hard to detect! The dynamic file should have the charset
ISO-8859-1
specified in its contentType (e.g.application/octet-stream; charset=ISO-8859-1
). If you experience caching issues, make sure that thedontCache
flag of the file is set totrue
When using page-based HTML headers and/or footers the following keys are appended to the request URL so they can be used directly in the page:
${request.page}
Replaced by the number of the pages currently being printed${request.frompage}
Replaced by the number of the first page to be printed${request.topage}
Replaced by the number of the last page to be printed${request.webpage}
Replaced by the URL of the page being printed${request.section}
Replaced by the name of the current section${request.subsection}
Replaced by the name of the current subsection${request.date}
Replaced by the current date in system local format${request.isodate}
Replaced by the current date in ISO 8601 extended format${request.time}
Replaced by the current time in system local format${request.title}
Replaced by the title of the of the current page object${request.doctitle}
Replaced by the title of the output document${request.sitepage}
Replaced by the number of the page in the current site being converted${request.sitepages}
Replaced by the number of pages in the current site being converted
Examples
1. Dynamic file which automatically downloads
(using 3 pages: 'pdf-export-main-page', 'pdf-export-header-page' and 'pdf-export-footer-page')
${{
// download pdf file as "my-downloaded-file.pdf"
$.setResponseHeader('Content-Disposition', 'attachment; filename="my-downloaded-file.pdf"');
$.set_response_header('Cache-Control', 'no-cache');
// These variables reference local pages in the structr installation
let main = 'pdf-export-main-page/';
let header = '--header-html ' + Structr.get('base_url') + '/pdf-export-header-page/';
let footer = '--footer-html ' + Structr.get('base_url') + '/pdf-export-footer-page/';
let wkhtmlArgs = header + ' ' + footer + ' --disable-smart-shrinking';
let pdf = Structr.pdf(main, wkhtmlArgs);
$.print(pdf);
}}
2. Creates a new file for each run of the script:
${set_content(create('File', 'name', 'new_document.pdf'), pdf('pdf-export-page'), 'ISO-8859-1')}
keyboard_arrow_rightkeyboard_arrow_downread()
Returns the contents of a file underneath the Structr exchange/
directory. See Anatomy of a Structr application for more information.
Usage
read(filepath)
Notes
The
exchange/
directory itself may be a symbolic linkUnderneath the
exchange/
the canonical path of a file has to be identical to the provided filepath in order to prevent directory traversal attacksThis means that symbolic links inside the
exchange/
directory are forbiddenAlso path traversal is forbidden
Example 1: Allowed ‘sub/dir/file.txt’
Example 2: Forbidden ‘../../../../etc/passwd’
Example 3: Forbidden ‘/etc/passwd’
Examples
${read('helloworld.txt')}
${read('subdir/helloworld.txt')}
Hello, world!
keyboard_arrow_rightkeyboard_arrow_downset_content()
Overwrites the contents of the given file with the given content.
Usage
set_content(file, content[, encoding = "UTF-8"])
Notes
The
encoding
parameter is used when writing the data to the file. The default (UTF-8
) rarely needs to be changed but can be very useful when working with binary strings. For example when using theto_excel()
function.
Examples
1. Simply overwrite file with static content
${set_content(first(find('File', 'name', 'test.txt')), 'New Content Of File test.txt')}
2. Create new file with Excel content
${set_content(create('File', 'name', 'new_document.xlsx'), to_excel(find('User'), 'public'), 'ISO-8859-1')}
3. Create a new file and retrieve the last 100 tweets from @structr
You first need to create a Twitter application and a corresponding bearer token (see https://developer.twitter.com/en/docs/basics/authentication/api-reference/token for more information)
${(
add_header('Authorization', 'Bearer <YOUR PERSONAL BEARER TOKEN GOES HERE>'),
set_content(create('File', 'name', 'structr-tweets.json'),
GET('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=structr&count=100'))
)}
4. Download binary data (an image) and store it in a local file
${set_content(create('File', 'name', 'google_logo.png'), GET('https://www.google.com/images/branding/googlelogo/1x/googlelogo_light_color_272x92dp.png', 'application/octet-stream'))}
keyboard_arrow_rightkeyboard_arrow_downwrite()
Writes a string representation of the given values to a file underneath the Structr exchange/
directory. See Anatomy of a Structr application for more information.
Usage
write(filepath, data...)
Notes
The
exchange/
directory itself may be a symbolic linkUnderneath the
exchange/
the canonical path of a file has to be identical to the provided filepath in order to prevent directory traversal attacksThis means that symbolic links inside the
exchange/
directory are forbiddenAlso path traversal is forbidden
Example 1: Allowed ‘sub/dir/file.txt’
Example 2: Forbidden ‘../../../../etc/passwd’
Example 3: Forbidden ‘/etc/passwd’
Examples
${write('info.txt', 'Hello, ', 'world!')}
${write('subdir/info.txt', 'Hello, ', 'world!')}
keyboard_arrow_rightkeyboard_arrow_downxml()
Tries to parse the contents of the given string into an XML document, returning the document on success. This method can be used in conjunction with read()
and xpath()
to read data from an XML file on disk.
Usage
xml(string)
Examples
${xml(read('test.xml'))}
[#document: null]
E-Mail Functions
Basic E-Mail Functions
keyboard_arrow_rightkeyboard_arrow_downsend_html_mail()
Sends an HTML e-mail with the given configuration. See Mail Configuration for more information. The e-mail methods are the main use-case for the template()
method.
Available from 2.0.2: An optional list of files (instances of File
) can be passed to the command. The files will be sent as e-mail attachments.
Usage
send_html_mail(fromAddress, fromName, toAddress, toName, subject, htmlContent, textContent [, attachments] )
Notes
Attachments have to be provided as a list - even if only one file should be attached.
Examples
${send_html_mail('info@structr.com', 'Structr', 'user@domain.com', 'Test User', 'Welcome to Structr', '<p>Hi <b>User</b>,</p><p>welcome to Structr!</p>', 'Hi User,\n\nwelcome to Structr!')}
keyboard_arrow_rightkeyboard_arrow_downsend_plaintext_mail()
Sends an e-mail with the given configuration. See Mail Configuration for more information. The e-mail methods are the main use-case for the template()
method.
Usage
send_plaintext_mail(fromAddress, fromName, toAddress, toName, subject, content)
Examples
${send_plaintext_mail('info@structr.com', 'Structr', 'user@domain.com', 'Test User', 'Welcome to Structr', 'Hi User, welcome to Structr!')}
Advanced E-Mail Functions
keyboard_arrow_rightkeyboard_arrow_downmail_begin()
Begins an HTML e-mail with the basic given configuration. See Mail Configuration for more information. The e-mail methods are the main use-case for the template()
method. The recipients are added via the mail_add_to()
, mail_add_cc()
and mail_add_bcc()
functions. This is separated out to allow for emails with only CC and/or BCC addresses.
An optional list of files (instances of File
) can be passed to the command. The files will be sent as e-mail attachments. For more granular control the mail_add_attachment()
function can be used.
This is a convenience method where we can supply multiple parameters at once. Alternatively we can use mail_set_from()
, mail_set_subject()
, mail_set_html_content()
, mail_set_text_content()
and mail_add_attachment()
. This is especially helpful if we are trying to send a series of mails with nearly identical content.
Usage
mail_begin(fromAddress [, fromName [, subject [, htmlContent [, textContent [, files]]]]] )
Notes
This function initially clears the current mail configuration completely (if a previous configuration in the same scripting context exists)
Attachments have to be provided as a list - even if only one file should be attached.
Examples
${mail_begin('info@structr.com', 'Structr', 'Welcome to Structr', 'Hi User, welcome to Structr!')}
keyboard_arrow_rightkeyboard_arrow_downmail_set_from()
Overwrites/Sets the from address (and optionally name) of the current mail.
Usage
mail_set_from(fromAddress [, fromName])
Examples
${mail_set_from('support@structr.com', 'Structr Support')}
keyboard_arrow_rightkeyboard_arrow_downmail_set_subject()
Overwrites/Sets the subject of the current mail.
Usage
mail_set_subject(subject)
Examples
${mail_set_subject('Reply for you support ticket')}
keyboard_arrow_rightkeyboard_arrow_downmail_set_html_content()
Overwrites/Sets the HTML content of the current mail.
Usage
mail_set_html_content(htmlContent)
Examples
${mail_set_html_content('<b>HTML</b> content')}
keyboard_arrow_rightkeyboard_arrow_downmail_set_text_content()
Sets/Overwrites the text content of the current mail.
Usage
mail_set_text_content(textContent)
Examples
${mail_set_text_content('Plaintext content')}
keyboard_arrow_rightkeyboard_arrow_downmail_add_to()
Adds a To:
recipient to the list of recipients. Can be called multiple times to add more recipients. The toName
can be omitted.
Usage
mail_add_to(toAddress [, toName] )
Examples
${mail_add_to('info@structr.com', 'Structr')}
keyboard_arrow_rightkeyboard_arrow_downmail_clear_to()
Clears the current list of To:
recipients.
Usage
mail_clear_to()
Examples
${mail_clear_to()}
keyboard_arrow_rightkeyboard_arrow_downmail_add_cc()
Adds a Cc:
recipient to the list of recipients. Can be called multiple times to add more recipients. The ccName
can be omitted.
Usage
mail_add_cc(ccAddress [, ccName] )
Examples
${mail_add_cc('info@structr.com', 'Structr')}
keyboard_arrow_rightkeyboard_arrow_downmail_clear_cc()
Clears the current list of Cc:
recipients.
Usage
mail_clear_cc()
Examples
${mail_clear_cc()}
keyboard_arrow_rightkeyboard_arrow_downmail_add_bcc()
Adds a Bcc:
recipient to the list of recipients. Can be called multiple times to add more recipients. The bccName
can be omitted.
Usage
mail_add_bcc(bccAddress [, bccName] )
Examples
${mail_add_bcc('info@structr.com', 'Structr')}
keyboard_arrow_rightkeyboard_arrow_downmail_clear_bcc()
Clears the current list of Bcc:
recipients.
Usage
mail_clear_bcc()
Examples
${mail_clear_bcc()}
keyboard_arrow_rightkeyboard_arrow_downmail_set_bounce_address()
Sets the bounce address - the address to which undeliverable messages will be returned if undeliverable.
Usage
mail_set_bounce_address(bounceAddress)
Examples
${mail_set_bounce_address('bounce@structr.com')}
keyboard_arrow_rightkeyboard_arrow_downmail_clear_bounce_address()
Removes the bounce address from the current mail.
Usage
mail_clear_bounce_address()
Examples
${mail_clear_bounce_address()}
keyboard_arrow_rightkeyboard_arrow_downmail_clear_reply_to()
Clears the current list of Reply-To:
addresses.
Usage
mail_clear_reply_to()
Examples
${mail_clear_reply_to()}
keyboard_arrow_rightkeyboard_arrow_downmail_add_reply_to()
Adds a Reply-To:
address to the current mail. The replyToName
can be omitted. Can be called multiple times.
Usage
mail_add_reply_to(replyToAddress[, replyToName])
Examples
${mail_add_reply_to('reply-to@structr.com')}
keyboard_arrow_rightkeyboard_arrow_downmail_add_attachment()
Adds a file (instances of File
) as an attachment to the mail. The name
parameter can be used to send the file with a different name than the filename in the Structr filesystem.
Usage
mail_add_attachment(fileNode [, name] )
Examples
${mail_add_attachment(first(find('File', 'name', 'static-file.txt')), 'renamed-static-file.txt')}
keyboard_arrow_rightkeyboard_arrow_downmail_clear_attachments()
Clears the attachments from the current mail.
Usage
mail_clear_attachments()
Examples
${mail_clear_attachments()}
keyboard_arrow_rightkeyboard_arrow_downmail_add_header()
Adds a custom header to the mail.
Usage
mail_add_header(name, value)
Notes
RFC 822 headers must contain only US-ASCII characters, so a header that contains non US-ASCII characters must have been encoded as per the rules of RFC 2047. Adding a non-compliant header will result in an error upon calling the
mail_send()
function.
Examples
${mail_add_header('X-Mailer', 'Structr')}
keyboard_arrow_rightkeyboard_arrow_downmail_remove_header()
Removes a single custom header from the mail.
Usage
mail_remove_header(name)
Examples
${mail_remove_header('X-Mailer')}
keyboard_arrow_rightkeyboard_arrow_downmail_clear_headers()
Clears any configured custom headers for the current mail.
Usage
mail_clear_headers()
Examples
${mail_clear_headers()}
keyboard_arrow_rightkeyboard_arrow_downmail_set_in_reply_to()
Indicates that the mail is a reply to the message with the given messageId
. This function automatically sets the In-Reply-To
header of the mail so that the receiving mail client can handle it correctly.
This function is especially interesting in conjunction with the mail_save_outgoing_message()
function.
Usage
mail_set_in_reply_to(messageId)
Examples
${mail_set_in_reply_to('<1910177794.5.1555059600315.JavaMail.username@machine.local>')}
keyboard_arrow_rightkeyboard_arrow_downmail_clear_in_reply_to()
Indicates that the next mail is not a reply to a message. This function automatically clears the In-Reply-To
header of the mail.
This function is only useful after sending a previous message with a configured In-Reply-To
.
Usage
mail_clear_in_reply_to()
Examples
${mail_clear_in_reply_to()}
keyboard_arrow_rightkeyboard_arrow_downmail_save_outgoing_message()
Configures the Advanced Mail Module that the next invocation of mail_send()
should save the outgoing email as an EMailMessage
node.
Configured attachments are copied and attached to the EMailMessage
node. For attached dynamic files the evaluated result is saved as a static file.
After the mail_send()
command is finished, the outgoing message can be accessed via mail_get_last_outgoing_message()
.
Usage
mail_save_outgoing_message(boolean)
Examples
${mail_save_outgoing_message(true)}
keyboard_arrow_rightkeyboard_arrow_downmail_get_last_outgoing_message()
Returns the outgoing message as the saved EMailMessage
node.
Usage
mail_get_last_outgoing_message()
Notes
This method will only yield a result if
mail_save_outoing_message()
is configured.
Examples
${mail_get_last_outgoing_message()}
keyboard_arrow_rightkeyboard_arrow_downmail_send()
Sends the currently configured mail and returns the message-id of the created mail.
If not all pre-conditions are met or the sending of the mail fails, an empty string will be returned and an error message is logged.
Since v3.6 the error message can be retrieved via mail_get_error()
and the presence of an error can be checked via mail_has_error()
. Before attempting to send the mail, the last error (if any) is cleared automatically.
Usage
mail_send()
Notes
Will result in an error if no
To:
,Cc:
orBcc:
addresses are configured.Will result in an error if
mail_begin()
was not called
Examples
${mail_send()}
keyboard_arrow_rightkeyboard_arrow_downmail_decode_text()
Decode “unstructured” headers, that is, headers that are defined as ‘*text’ as per RFC 822.
The string is decoded using the algorithm specified in RFC 2047, Section 6.1. If the charset-conversion fails for any sequence, it is returned as-is.
If the String is not an RFC 2047 style encoded header, it is also returned as-is
Usage
mail_decode_text(text)
Examples
${mail_decode_text('=?utf-8?Q?h=C3=A4llo?=')}
hällo
keyboard_arrow_rightkeyboard_arrow_downmail_encode_text()
Encode a RFC 822 “text” token into mail-safe form as per RFC 2047.
The given Unicode string is examined for non US-ASCII characters. If the string contains only US-ASCII characters, it is returned as-is. If the string contains non US-ASCII characters, it is first character-encoded using the platform’s default charset, then transfer-encoded using either the B or Q encoding. The resulting bytes are then returned as a Unicode string containing only ASCII characters.
Note that this method should be used to encode only “unstructured” RFC 822 headers.
Usage
mail_encode_text(text)
Examples
${mail_encode_text('hällo')}
=?utf-8?Q?h=C3=A4llo?=
keyboard_arrow_rightkeyboard_arrow_downmail_select_config()
Allows selecting a different SMTP configuration (as configured in structr.conf) for the current outgoing mail. The 6 SMTP settings can be overridden individually by adding a prefixed configuration entry. If no entry is found the default (non-prefixed) value is used.
Usage
mail_select_config(name)
Notes
A manual configuration overrides a selected configuration which overrides the default configuration.
Calling this function with an empty string deselects a previously selected configuration.
Examples
${mail_select_config('myDifferentConfig')}
**Example structr.conf**
[...]
smtp.host = <server>
smtp.port = <port>
smtp.user = <user>
smtp.password = <password>
smtp.tls.enabled = true
smtp.tls.required = true
myDifferentConfig.smtp.host = <server>
myDifferentConfig.smtp.port = <port>
myDifferentConfig.smtp.user = <user>
myDifferentConfig.smtp.password = <password>
myDifferentConfig.smtp.tls.enabled = true
myDifferentConfig.smtp.tls.required = true
[...]
keyboard_arrow_rightkeyboard_arrow_downmail_set_manual_config()
New in v3.6: Allows setting completely manual/dynamic SMTP configuration for the current outgoing mail.
Usage
mail_set_manual_config(smtpHost = 'localhost', smtpPort = 25, smtpUser = null, smtpPassword = null, smtpUseTLS = true, smtpRequireTLS = true)
Notes
A manual configuration overrides a selected configuration which overrides the default configuration.
If no value is provided for
smtpUser
and/orsmtpPassword
, the givensmtpHost
will be contacted without authentication.
Examples
${mail_set_manual_config('smtp.example.com', 587, 'myUser', 'password', true, true)}
keyboard_arrow_rightkeyboard_arrow_downmail_reset_manual_config()
New in v3.6: Allows resetting a previously set manual/dynamic SMTP configuration for the current outgoing mail.
Usage
mail_reset_manual_config()
Examples
${mail_reset_manual_config()}
keyboard_arrow_rightkeyboard_arrow_downmail_has_error()
New in v.3.6: Allows to check for errors when sending a mail.
Usage
${mail_has_error()}
Examples
${{
$.mail_begin('user@example.com', 'User', 'Test Mail', '<b>HTML</b> message', 'plain text message');
$.mail_add_to('another-user@example.com');
$.mail_send();
$.log($.mail_has_error());
}}
true if an error occurred - false if not.
keyboard_arrow_rightkeyboard_arrow_downmail_get_error()
New in v.3.6: Allows to retrieve the last error message when sending a mail.
Usage
${mail_get_error()}
Examples
${{
$.mail_begin('user@example.com', 'User', 'Test Mail', '<b>HTML</b> message', 'plain text message');
$.mail_add_to('another-user@example.com');
$.mail_send();
if ($.mail_has_error()) {
// react to error here
$.log($.mail_get_error());
}
}}
(example error)
Sending the email to the following server failed : smtp.example.com:587
535-5.7.8 Username and Password not accepted.
Miscellaneous Functions
keyboard_arrow_rightkeyboard_arrow_downassert()
Aborts the current request if the given condition evaluates to false and returns the given error message with the status code.
Usage
assert(condition, statusCode, message)
Notes
Only works as intended in schema methods - not in page rendering.
Examples
assert(eq(me.name, 'admin'), 422, 'Only admin account is allowed to access this resource')
keyboard_arrow_rightkeyboard_arrow_downbarcode()
Creates a barcode image of the given type with the given data using the zxing library. The library supports several different barcode types.
Barcode Type | Result |
---|---|
AZTEC | Aztec 2D barcode format (beta) |
CODABAR | CODABAR 1D format |
CODE_39 | Code 39 1D format |
CODE_93 | Code 93 1D format |
CODE_128 | Code 128 1D format |
DATA_MATRIX | Data Matrix 2D barcode format |
EAN_8 | EAN-8 1D format |
EAN_13 | EAN-13 1D format |
ITF | ITF (Interleaved Two of Five) 1D format |
PDF_417 | PDF417 format (beta) |
QR_CODE | QR Code 2D barcode format |
UPC_A | UPC-A 1D format |
UPC_E | UPC-E 1D format |
Usage
barcode(type, data[, width = 200, height = 200 [, hintKey, hintValue, ...]])
$.barcode(type, data[, width = 200, height = 200 [, hintMap]])
Notes
Most barcode types support different hints which are explained under here. Probably the most interesting hints are
MARGIN
andERROR_CORRECTION
. Following is an excerpt from the source code. More information on the error correction level can be found hereMARGIN: Specifies margin, in pixels, to use when generating the barcode. The meaning can vary by format; for example it controls margin before and after the barcode horizontally for most 1D formats. (Type Integer, or String representation of the integer value).
ERROR_CORRECTION: Specifies what degree of error correction to use, for example in QR Codes. Type depends on the encoder. For example for QR codes it’s type ErrorCorrectionLevel. For Aztec it is of type Integer, representing the minimal percentage of error correction words. For PDF417 it is of type Integer, valid values being 0 to 8. In all cases, it can also be a String representation of the desired value as well. Note: an Aztec symbol should have a minimum of 25% EC words.
Examples
(1) Usage in a dynamic file
- File content: ${barcode('QR_CODE', 'My testcode', 200, 200, "MARGIN", 0, "ERROR_CORRECTION", "Q")}
- File content-type: image/png;charset=ISO-8859-1
(2) Usage in a HTML IMG tag
- src attribute: data:image/png;base64, ${base64encode(barcode('QR_CODE', 'My testcode', 200, 200, 'MARGIN', 0, 'ERROR_CORRECTION', 'Q'), 'basic', 'ISO-8859-1')}
keyboard_arrow_rightkeyboard_arrow_downbatch()
Enables batching for the given expression, i.e. if the expression contains a long-running function (for example the deletion of all nodes of a given type, see examples below), that function will be instructed to commit its results in batches of batchSize
.
Useful in situations where large numbers of nodes are created, modified or deleted in a StructrScript expression.
In JavaScript the batch() function takes a worker function as its first parameter and an optional error handler function as its second parameter. If the worker function returns true
, it is run again. If it returns anything else it is not run again. If an exception occurs in the worker function, the error handler function (if present) is called. If the error handler returns true
, the worker function is called again. If the error handler function returns anything else (or an exception occurs) the worker function is not run again.
Usage
batch(expression, batchSize)
// DEPRECATED in JavaScript!
$.batch(workerFunction [, errorHandlerFunction ] )
Notes
IMPORTANT: With Structr 4.0 the JavaScript version $.batch function has been renamed to $.doInNewTransaction to better communicate the semantics!
The JavaScript version of batch() is a prime candidate for an endless loop - be careful what your return condition is!
Because of the asynchronous nature of
batch()
, it is not possible to use it in a page to create output viaprint()
.
Examples
${batch(delete(find('Item')), 1000)}
${batch(each(find('Item'), set(data, "visibleToPublicUsers", true)), 1000)}
${{
/* Iterate over all users in packets of 10 and do stuff */
let pageSize = 10;
let pageNo = 1;
$.batch(function() {
let nodes = $.find('User', $.predicate.page(pageNo, pageSize)); // in structr versions lower than 4.0 replace "$.predicate.page" with "$.page"
// compute-heavy stuff
pageNo++;
return (nodes.length > 0);
}, function() {
$.log('Error occurred in batch function. Stopping.');
return false;
});
}}
keyboard_arrow_rightkeyboard_arrow_downbroadcast_event()
Triggers the sending of a sever-sent event all authenticated and/or anonymous users with an open connection.
Usage
broadcast_event(eventType, message [, authenticatedUsers = true [ , anonymousUsers = false ]] )
Examples
broadcast_event('myTopic', 'Topic message', true, false)
$.broadcastEvent('myJSONTopic', JSON.stringify({id: 'APP_MAINTENANCE_SOON', message: 'Application going down for maintenance soon!', date: new Date().getTime()}), true, false);
keyboard_arrow_rightkeyboard_arrow_downcache()
This method can be used to store a value (which is costly to obtain or should not be updated frequently) under the given key in a global cache. The method will execute the given valueExpression to obtain the value, and store it for the given time (in seconds). All subsequent calls to the cache()
method will return the stored value (until the timeout expires) instead of evaluating the valueExpression
.
Usage
cache(key, timeout, valueExpression)
Notes
Since subsequent calls to cache() will return the previous result it can be desirable to delete the previous value in order to be able to store a new value. This can be done via the
delete_cache_value()
function.Usage in JavaScript is almost identical, but a complex
valueExpression
needs to be wrapped in an anonymous function so execution can be skipped if a valid cached value is present. If no anonymous function is used, the code is always executed and thus defeats the purpose of using$.cache()
Examples
${cache('externalResult', 3600, GET('http://api.myservice.com/get-external-result'))}
${{
// (1) Simple example
$.cache('myCacheKey', 3600, 'initialCacheValue');
$.cache('myCacheKey', 3600, 'test test test');
$.log($.cache('myCacheKey', 3600, 'test 2 test 2 test 2'));
/* will log `initialCacheValue` to the server log. */
(2) Lazily evaluated example
$.cache('externalResult', 3600, () => {
return $.GET('http://api.myservice.com/get-external-result');
});
}}
keyboard_arrow_rightkeyboard_arrow_downconfig()
Returns the configuration value associated with the given key from structr.conf. This method can be used to read arbitrary values from the configuration file and use it to configure frontend behaviour, default values etc. The optional second parameter is the default value to be returned if the configuration key is not present.
Usage
config(key[, default])
Notes
For security reasons the superuser password can not be read with this function.
Examples
${config('files.path')}
${config('some.unconfigured.key', 'default value')}
./files
default value
keyboard_arrow_rightkeyboard_arrow_downcreate_access_token()
Creates an JWT access_token
for the given User entity that can be used for request authentication
Usage
create_access_token(user [, accessTokenTimeout])
Examples
${create_access_token(me [, 15])}
eyJhbGciOiJIUzUxMiJ9.eyJ[...]2Q1In0.K_o-mIjzJZlr3pWOjYBotD_JUeGZ1sS5necqKhfpfhy8yTbaKxRtpPMafBpQEvcH6dmKZ9kNhu5PGkvtKE_MFA
keyboard_arrow_rightkeyboard_arrow_downcreate_access_and_refresh_token()
Creates an JWT access_token
together with an refresh_token
for the given User entity that can be used for request authentication and authorization.
Usage
create_access_and_refresh_token(user [, accessTokenTimeout, refreshTokenTimeout])
Examples
${create_access_and_refresh_token(me, 15, 60)}
{
"access_token":"eyJhbGciOiJIUzUxMiJ9.eyJ[...]VkIn0.fbwKEQ4dELHuXXmPiNtn8XNWh6ShesdlTZsXf-CojTmxQOWUxkbHcroj7gVz02twox82ChTuyxkyHeIoiidU4g",
"refresh_token":"eyJhbGciOiJIUzUxMiJ9.eyJ[...]lbiJ9.GANUkPH09pBimd5EkJmrEbsYQhDw6hXULZGSldHSZYqq1FNjM_g6wfxt1217TlGZcjKyXEL_lktcPzjOe_eU3A",
"expiration_date":"1616692902820"
}
keyboard_arrow_rightkeyboard_arrow_downhmac()
Returns a keyed-hash message authentication code generated out of the given payload, secret and hash algorithm.
Usage
hmac(value, secret [, hashAlgorithm ])
Notes
Default value for parameter hashAlgorithm is SHA256.
Examples
$.hmac(JSON.stringify({key1: "test"}), "aVeryGoodSecret")
5d1ab1de51a9e23d52dfb12a6b355420e84ca467b0071d2a58d9915e383e09d5
keyboard_arrow_rightkeyboard_arrow_downdoInNewTransaction()
Removes the given function form the current transaction context and allows batching of a given expression, i.e. if the expression contains a long-running function (for example the deletion of all nodes of a given type, see examples below), that function will be instructed to commit its results in batches of batchSize
.
Useful in situations where large numbers of nodes are created, modified or deleted.
This function is only available in JavaScript and takes a worker function as its first parameter and an optional error handler function as its second parameter. If the worker function returns true
, it is run again. If it returns anything else it is not run again. If an exception occurs in the worker function, the error handler function (if present) is called. If the error handler returns true
, the worker function is called again. If the error handler function returns anything else (or an exception occurs) the worker function is not run again.
New in v4.0: The errorHandler
function now has a parameter where the error(/exception) is available. Depending on the error type, different methods are available on that object. Syntax errors will yield a PolyglotException
(see https://www.graalvm.org/sdk/javadoc/org/graalvm/polyglot/PolyglotException.html), other error types will yield different exception object. See example 4 for more information.
Usage
$.doInNewTransaction(workerFunction [, errorHandlerFunction] )
Notes
WARNING: This function is a prime candidate for an endless loop - be careful what your return condition is!
WARNING: You have to be aware of the transaction context. Anything from the outermost transaction is not yet committed to the graph and thus can not be used to connect to in an inner transaction. The outer transaction context is only committed after the method is finished without a rollback. See example (2) for code which will result in an error and example (3) for a solution
Examples
(1) Regular working example
${{
/* Iterate over all users in packets of 10 and do stuff */
let pageSize = 10;
let pageNo = 1;
$.doInNewTransaction(function() {
let nodes = $.find('User', $.predicate.page(pageNo, pageSize)); // in structr versions lower than 4.0 replace "$.predicate.page" with "$.page"
// compute-heavy stuff
pageNo++;
return (nodes.length > 0);
}, function() {
$.log('Error occurred in batch function. Stopping.');
return false;
});
}}
(2) Example where the inner transaction tries to create a relationship to a node which has not yet been committed and thus the whole code fails
${{
/* create a new group */
let group = $.getOrCreate('Group', 'name', 'ExampleGroup');
$.doInNewTransaction(() => {
let page = $.create('Page', 'name', 'ExamplePage');
/* this is where the error occurs - the Group node is not yet committed to the graph and when this context is closed a relationship between the group and the page is created - which can not work because only the page is committed to the graph */
$.grant(group, page, 'read');
});
}}
(3) Example to fix the problems of example (2)
${{
/* create a new group */
let groupId;
$.doInNewTransaction(() => {
let group = $.getOrCreate('Group', 'name', 'ExampleGroup');
/* save the group id to be able to fetch it later */
groupId = group.id;
/* after this context, the group is committed to the graph and relationships to it can later be created */
});
$.doInNewTransaction(() => {
let page = $.create('Page', 'name', 'ExamplePage' });
/* fetch previously created group */
let group = $.find('Group', groupId);
/* this works now */
$.grant(group, page, 'read');
});
}}
(4) Example where an error occurs and is handled (v4.0+)
${{
$.doInNewTransaction(() => {
let myString = 'the following variable is undefined ' + M;
}, (ex) => {
// depending on the exception type different methods will be available
$.log(ex.getClass().getSimpleName());
$.log(ex.getMessage());
});
}
keyboard_arrow_rightkeyboard_arrow_downdecrypt()
Decrypts a base 64 encoded AES ciphertext and returns the decrypted result. This method either uses the internal global encryption key that is stored in structr.conf, or the optional second parameter.
Usage
decrypt(text [, secret ] )
Examples
${print(decrypt(get(this, 'encryptedString'))}
${print(decrypt(get(this, 'encryptedString'), 'secret key')}
keyboard_arrow_rightkeyboard_arrow_downdelete_cache_value()
Removes the cached value for the given key (if present).
Usage
delete_cache_value(key)
Examples
${delete_cache_value('externalResult')}
keyboard_arrow_rightkeyboard_arrow_downdisable_notifications()
Temporarily disables the Websocket Broadcast notifications for the Structr Backend UI. This method can be used to prevent the broadcasting of large modification operations which greatly reduces the processing time for such large operations. If you experience very slow (i.e. more than 10 seconds) object creation, modification or deletion, try to disable notifications before executing the operation. See also enable_notifications()
.
Usage
disable_notifications()
Notes
This can be done on a per-request basis by sending the custom HTTP header
Structr-Websocket-Broadcast
with a value ofdisabled
along with the request.
keyboard_arrow_rightkeyboard_arrow_downenable_notifications()
This method is the inverse of disable_notifications()
. It re-enabled the Websocket broadcast of creation, modification and deletion operations. See disable_notifications()
for more information on that topic.
Usage
enable_notifications()
keyboard_arrow_rightkeyboard_arrow_downencrypt()
Encrypts the given string using AES and returns the ciphertext encoded in base 64. This method either uses the internal global encryption key that is stored in structr.conf, or the optional second parameter.
Usage
encrypt(text [, secret ] )
Examples
${set(this, 'encryptedString', encrypt('example string'))}
${set(this, 'encryptedString', encrypt('example string', 'secret key'))}
keyboard_arrow_rightkeyboard_arrow_downerror()
This method can be used to signal an error condition while scripting execution. It is mainly used in entity callback functions like onCreate()
or onSave()
to allow the user to implement custom validation logic.
If an error is raised the current transaction will be rolled back and no changes will be written to the database.
Usage
error(propertyKey, token, detail)
error(propertyKey, token)
Examples
${error('name', 'name_not_allowed')}
${error('name', 'name_not_allowed', 'The given name is not allowed.')}
results in an HTTP 422 Unprocessable Entity error.
keyboard_arrow_rightkeyboard_arrow_downevaluate_script()
Evaluates the given script in the context of given entity.
Usage
evaluate_script(entity, script)
Notes
This function poses a very severe security risk if you are using it with user-provided content!
Examples
${evaluate_script(me, "print(this.name)")}
results in the name of the current user being printed.
keyboard_arrow_rightkeyboard_arrow_downget_cache_value()
Retrieves the cached value for the given key.
Returns null if there is no stored value for the given key or if the stored value is expired.
Usage
get_cache_value(key)
Examples
${get_cache_value('externalResult')}
keyboard_arrow_rightkeyboard_arrow_downgetenv()
Gets all environment variables or the value of the specified environment variable. An environment variable is a system-dependent external named value.
If no variable is given, a map of all environment variables is returned.
Usage
getenv()
getenv(variable)
Notes
This function was added in v4.0
Examples
${getenv('JAVA_HOME')}
${{ return $.getenv().PATH; }}
keyboard_arrow_rightkeyboard_arrow_downget_session_attribute()
Retrieves a value stored under the given key from the user session.
Usage
get_session_attribute(key)
Examples
${get_session_attribute('do_not_track')}
keyboard_arrow_rightkeyboard_arrow_downhas_cache_value()
Checks if a cached value exists for the given key. Returns false if there is no stored value for the given key or if the stored value is expired.
This function is especially useful if the result of a JavaScript function should be cached (see Example 2).
Usage
has_cache_value(key)
Examples
(1) ${has_cache_value('externalResult')}
(2)
${{
let myComplexFunction = function() {
// computation... for brevity just return a date string
return new Date().toString();
};
let cacheKey = 'myKey';
if (Structr.hasCacheValue(cacheKey)) {
// retrieve cached value
let cacheValue = Structr.getCacheValue(cacheKey);
// ...
// ...
} else {
// cache the result of a complex function
let cacheResult = Structr.cache(cacheKey, 30, myComplexFunction());
// ...
// ...
}
}}
keyboard_arrow_rightkeyboard_arrow_downhas_error()
Allows checking if an error has been raised in the scripting context
Usage
has_error()
keyboard_arrow_rightkeyboard_arrow_downis_locale()
Returns a boolean value that indicates whether the locale of the current context is one of the given locale values.
Usage
is_locale(locales, ...)
Notes
See the locale keyword to learn how the locale of the current context is determined.
Examples
${is_locale('de_DE', 'de_AT')}
true
keyboard_arrow_rightkeyboard_arrow_downjdbc()
Fetches data from a JDBC source. Since version 3.3.1, you can define the driver class by setting the full qualified class path in the driver
parameter.
The default for the driver
parameter is com.mysql.jdbc.Driver
.
Usage
jdbc(url, query)
New with 3.3.1:
jdbc(url, query[, driver])
Notes
Make sure the driver specific to your SQL server is available in a JAR file in Structr’s lib directory (
/usr/lib/structr/lib
in debian installations). Other JAR sources are availble for Oracle (https://www.oracle.com/technetwork/database/application-development/jdbc/downloads/index.html) or MSSQL (https://docs.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server). For more JARs for specific SQL Servers, please consult the documentation for that specific server.
Examples
${jdbc("jdbc:mysql://localhost:3306", "SELECT * from Test")}
New with 3.3.1:
You can now define the exact driver class:
${jdbc("jdbc:oracle:thin:user/password@myhost:1521:orcl", "SELECT * from Test", "oracle.jdbc.driver.OracleDriver")}
The following example shows how to use the `jdbc()` function to import data from an Oracle database:
{ // JavaScript Context
let rows = $.jdbc('jdbc:oracle:thin:test/test@localhost:1521:orcl', 'SELECT * FROM test.emails');
rows.forEach(function(row) {
$.log('Fetched row from Oracle database: ', row);
let fromPerson = $.getOrCreate('Person', 'name', row.from_address);
let toPerson = $.getOrCreate('Person', 'name', row.to_address);
let message = $.getOrCreate('EMailMessage',
'content', row.email_body,
'sender', fromPerson,
'recipient', toPerson,
'sentDate', $.parseDate(row.email_date, 'yyyy-MM-dd')
);
$.log('Found existing or created new EMailMessage node: ', message);
});
}
keyboard_arrow_rightkeyboard_arrow_downjob_info()
Returns information about the job with the given job Id. If the job does not exist (anymore) the function returns false
.
For script jobs the returned information is:
Key | Value |
---|---|
jobId | The job ID |
jobtype | The job type |
username | The username of the user who started the job |
status | The current status of the job |
jobName | The name of the script job |
exception | If an exception was caught during the execution, an exception object containing:
|
For file import the returned information is:
Key | Value |
---|---|
jobId | The job ID |
jobtype | The job type |
username | The username of the user who started the job |
status | The current status of the job |
fileUuid | The UUID of the imported file |
filepath | The path of the imported file |
filesize | The size of the imported file |
processedChunks | The number of chunks already processed |
processedObjects | The number of objects already processed |
exception | If an exception was caught during the execution, an exception object containing:
|
Usage
job_info(jobId)
Examples
${job_info(1)}
keyboard_arrow_rightkeyboard_arrow_downlog_event()
Creates an entity of type LogEvent
with the current timestamp and the given values.
All four parameters (action
, message
, subject
and object
) can be arbitrary strings.
In JavaScript, the function can be called with a single map as parameter. The event paramters are taken from that map.
Usage
log_event(action, message [, subject [, object ]])
$.logEvent(map)
Examples
${log_event('VIEW', me.id)}
${{
$.logEvent({
action: "VIEW",
message: Structr.me.id
});
}}
keyboard_arrow_rightkeyboard_arrow_downmaintenance()
Allows an admin user to execute a maintenance command from within a scripting context.
Usage
maintenance(commandName [, key1, value1 [, ... ]])
$.maintenance(commandName [, map ])
Notes
In a StructrScript environment parameters are passed as pairs of ‘key1’, ‘value1’.
In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
Examples
${maintenance('rebuildIndex')}
${{
$.maintenance('rebuildIndex', { type: 'Article' });
}}
keyboard_arrow_rightkeyboard_arrow_downmongodb()
Opens a connection to a MongoDB source and returns a MongoCollection which can be used to further query the Mongo database. Available since version 4.0
Usage
mongodb(connectionString, database, collection)
Notes
The returned MongoCollection object has the functions exposed as described in https://mongodb.github.io/mongo-java-driver/4.2/apidocs/mongodb-driver-sync/com/mongodb/client/MongoCollection.html
Native MongoDB operators (https://docs.mongodb.com/manual/reference/operator/) can be used
Every function without parameters or with Bson parameter can be used
Creating a Bson object is done with the
$.bson()
function which simple converts a JSON object to BsonThe result of a
collection.find()
is not a native JS array, so functions like.filter()
or.map()
are not available - thefor of
syntax appliesThe records in a result are also not native JS objects, so the dot notation (i.e.
record.name
) does not work - therecord.get('name')
syntax applies
Examples
NOTE: All examples assume a mongo instance has been locally started via docker with the following command: docker run -ti -p 27017:27017 mongo
(1) Open connection, insert object and retrieve objects with identical name
{
// Open the connection to mongo and return the testCollection
let collection = $.mongodb('mongodb://localhost', 'testDatabase', 'testCollection');
// Insert a record
collection.insertOne($.bson({
name: 'Test4'
}));
// Query all records with a give property set
return collection.find($.bson({ name: 'Test4' }));
}
(2) Open connection and find objects with regex name
{
// Open the connection to mongo and return the testCollection
let collection = $.mongodb('mongodb://localhost', 'testDatabase', 'testCollection');
// Query all records with a give property set
return collection.find($.bson({ name: { $regex: 'Test[0-9]' } }));
}
(3) Open connection, insert object with date and query all objects with dates greater than equal (gte) that date
{
// Open the connection to mongo and return the testCollection
let collection = $.mongodb('mongodb://localhost', 'testDatabase', 'testCollection');
// Insert a record
collection.insertOne($.bson({
name: 'Test9',
date: new Date(2018, 1, 1)
}));
return collection.find($.bson({ date: { $gte: new Date(2018, 1, 1) } }));
}
(1) objects with name 'Test4'
(2) objects with name 'Test' + a single digit
(3) objects with dates greater than equal (gte) that date
keyboard_arrow_rightkeyboard_arrow_downr()
Interpretes R code. (See the Scripting Guide for more info on supported languages)
Usage
r(<R code>)
keyboard_arrow_rightkeyboard_arrow_downrandom_uuid()
New in v3.6: Returns a new random UUID, a string with 32 characters [0-9a-f].
Usage
random_uuid()
Examples
${{
var newId = $.randomUuid();
return newId;
}}
dda27cc07ac34c75a121d6e1821c1851
keyboard_arrow_rightkeyboard_arrow_downremove_session_attribute()
Removes a value stored under the given key from the user session.
Usage
remove_session_attribute(key)
Examples
${remove_session_attribute('do_not_track')}
keyboard_arrow_rightkeyboard_arrow_downretrieve()
Retrieves the value previously stored under the given key in the current request context. This method can be used to obtain the results of a previous computation step etc. and is often used to provide some sort of “variables” in the scripting context. See store()
for the inverse operation.
Additionally, the retrieve()
function is used to retrieve the parameters supplied to the execution of a custom method.
Usage
retrieve(key)
Examples
${retrieve('users')}
[admin, user1, user2, user3]
keyboard_arrow_rightkeyboard_arrow_downschedule()
Allows the user to insert a script snippet into the import queue for later execution. Useful in situations where a script should run after a long-running import job, or if the script should run in a separate transaction that is independent of the calling transaction.
The title
parameter is optional and is displayed in the structr admin UI in the Importer section and in the notification messages when a script is started or finished.
The onFinish
parameter is a script snippet which will be called when the process finishes (successfully or with an exception).
A parameter jobInfo
is injected in the context of the onFinish
function (see job_info()
for more information on this object).
The schedule function returns the job id under which it is registered.
Usage
schedule(expression [, title [, onFinish ]])
Examples
${schedule('call("myCleanupScript")', 'Cleans unconnected nodes from the graph')}
**JavaScript Example**
${{
$.schedule(function() {
// execute global method
Structr.call('myCleanupScript');
}, 'Cleans unconnected nodes from the graph');
}}
${{
$.schedule(function() {
// execute global method
Structr.call('myCleanupScript');
}, 'Cleans unconnected nodes from the graph', function() {
Structr.log('scheduled function finished!');
Structr.log('Job Info: ', Structr.get('jobInfo'));
});
}}
keyboard_arrow_rightkeyboard_arrow_downsend_event()
Triggers the sending of a sever-sent event to a given list of recipients. The message will only be sent if they have an open connection.
Usage
send_event(eventType, message, recipient(s))
Notes
Recipients can either be a single user, a single group or a mixed list of both.
Examples
send_event("myTopic", "Welcome Bob!", find('User', 'name', 'Bob'))
keyboard_arrow_rightkeyboard_arrow_downserverlog()
Returns the last n lines from the server log file
Usage
serverlog([lines = 50])
Examples
${serverlog(200)}
keyboard_arrow_rightkeyboard_arrow_downset_encryption_key()
Sets the internal global encryption key that is used by the encrypt()
and decrypt()
functions. Please note that this method overwrites the encryption key that is stored in structr.conf. The overwritten key can be restored by using null
as a parameter to this method, as shown in the example below
Usage
set_encryption_key(secret)
Examples
${set_encryption_key('secret key')}
${set_encryption_key(null)}
keyboard_arrow_rightkeyboard_arrow_downset_locale()
Sets the locale for the current scripting context. This setting directly influences the result of date parsing and formatting functions.
Usage
set_locale(locale)
Examples
${set_locale('de')}
keyboard_arrow_rightkeyboard_arrow_downset_session_attribute()
This method can be used to store a value under the given key in the user session.
Usage
set_session_attribute(key, value)
Examples
${set_session_attribute('do_not_track', true)}
keyboard_arrow_rightkeyboard_arrow_downsleep()
Causes the execution flow to wait / sleep for the given number of milliseconds.
Usage
sleep(milliseconds)
Examples
${sleep(1000)}
keyboard_arrow_rightkeyboard_arrow_downstore()
Stores the given value in the current request context under the given key. This method can be used to temporarily save the results of a computation step etc. and is often used to provide some sort of “variables” in the scripting context. See retrieve()
for the inverse operation.
Usage
store(key, value)
Examples
${store('users', find('User'))}
keyboard_arrow_rightkeyboard_arrow_downsystem_info()
New in v3.6: Returns a number of system parameters.
Key | Value |
---|---|
now | Current time in ms |
uptime | Time in ms since the application started |
runtime | Version string of the java runtime |
counts | number of nodes and relationships in the database (if connected) |
caches | Size and max size of the node/relationship/localizations caches |
memory | Memory information gathered from the runtime and from management beans (in bytes) |
Usage
system_info()
Examples
system_info()
{now=1592312051572, uptime=877700, runtime=11.0.7+8-LTS, counts={nodes=9334, relationships=13878}, caches={node={size=9334, max=100000}, relationship={size=3806, max=500000}, localizations={size=0, max=10000}}, memory={runtime_info={free=361822224, max=8589934592, total=1289748480}, mgmt_bean_info={G1 Eden Space={i
nit=56623104, used=0, committed=740294656, max=-1}, G1 Old Gen={init=1017118720, used=0, committed=0, max=8589934592}, G1 Survivor Space={init=0, used=73400320, committed=73400320, max=-1}}}}
keyboard_arrow_rightkeyboard_arrow_downtimer()
This method can be used to measure the performance of sections of code. The action
parameter can be start
to create a new timer or get
to retrieve the elapsed time (in milliseconds) since the start of the timer.
Usage
timer(name, action)
Notes
Using the
get
action before thestart
action returns 0 and starts the timer.Using the
start
action on an already existing timer overwrites the timer.
Examples
${timer('benchmark', 'start')}
[...]
${log(timer('benchmark', 'get'), 'ms since timer started')}
keyboard_arrow_rightkeyboard_arrow_downtranslate()
Translates the given text via the a translation API.
Supported translation providers:
- google (Google Cloud Translation API, default)
- deepl (DeepL REST API)
Usage
translate(text, sourceLanguage, targetLanguage [, translationProvider] )
Notes
An API Key has to be configured in structr.conf.
See the documentation on the Translation module for more info.
Examples
${translate("Structr is awesome", "en", "de")}
Structr ist großartig
Numerical Functions
keyboard_arrow_rightkeyboard_arrow_downadd()
Returns the sum of all the values.
Usage
add(values...)
Examples
${add(1, 2, 3, 4)}
10
keyboard_arrow_rightkeyboard_arrow_downceil()
Returns the given value, rounded up to the nearest integer. This method tries to convert its parameter objects into numerical values, i.e. you can use strings as arguments.
Usage
ceil(val)
Examples
${ceil(5.8)}
6.0
keyboard_arrow_rightkeyboard_arrow_downdiv()
Returns the division result of parameter1 divided by parameter2.
Usage
div(parameter1, parameter2)
Examples
${div(5, 2)}
2.5
keyboard_arrow_rightkeyboard_arrow_downfloor()
Returns the given value, rounded down to the nearest integer. This method tries to convert its parameter objects into numerical values, i.e. you can use strings as arguments.
Usage
floor(val)
Examples
${floor(5.8)}
5.0
keyboard_arrow_rightkeyboard_arrow_downint()
Tries to convert the given object into an integer value.
Usage
int(object)
Examples
${int('23')}
${int(23.456)}
23
keyboard_arrow_rightkeyboard_arrow_downlong()
Tries to convert the given object into a long value.
Usage
long(object)
Notes
This function is especially helpful when trying to set a date value in the database via the
cypher()
function.Real dates are converted to the number of milliseconds since January 1, 1970, 00:00:00 GMT.
Date Strings are also supported in the following formats:
“yyyy-MM-dd’T’HH:mm:ss.SSSXXX”
“yyyy-MM-dd’T’HH:mm:ssXXX”
“yyyy-MM-dd’T’HH:mm:ssZ”
“yyyy-MM-dd’T’HH:mm:ss.SSSZ”
Examples
${long(now)}
1589407200000
keyboard_arrow_rightkeyboard_arrow_downmax()
Returns the greater of the given values. This method tries to convert its parameter objects into numerical values, i.e. you can use strings as arguments. See also min()
.
Usage
max(val1, val2)
Examples
${max(5, 8)}
8.0
keyboard_arrow_rightkeyboard_arrow_downmin()
Returns the smaller of the given values. This method tries to convert its parameter objects into numerical values, i.e. you can use strings as arguments. See also max()
.
Usage
min(val1, val2)
Examples
${min(5, 8)}
5.0
keyboard_arrow_rightkeyboard_arrow_downmod()
Returns the remainder of the quotient of val1 and val2. This method tries to convert its parameter objects into numerical values, i.e. you can use strings as arguments.
Usage
mod(val1, val2)
Examples
${mod(5, 2)}
1.0
keyboard_arrow_rightkeyboard_arrow_downmult()
Returns the product of all given parameters.
Usage
mult(val1, val2...)
Notes
This method tries to convert its parameter objects into numerical values, i.e. you can use strings as arguments.
Examples
${mult(5, 2, 3, "10")}
300.0
keyboard_arrow_rightkeyboard_arrow_downnum()
Returns the given numerical string as an actual number with double precision.
Usage
num(numericalString)
Notes
Real dates are converted to the number of milliseconds since January 1, 1970, 00:00:00 GMT.
Date Strings are also supported in the following formats:
“yyyy-MM-dd’T’HH:mm:ss.SSSXXX”
“yyyy-MM-dd’T’HH:mm:ssXXX”
“yyyy-MM-dd’T’HH:mm:ssZ”
“yyyy-MM-dd’T’HH:mm:ss.SSSZ”
Examples
${num('23')}
23.0
keyboard_arrow_rightkeyboard_arrow_downquot()
Returns the quotient of val1 and val2. This method tries to convert its parameter objects into numerical values, i.e. you can use strings as arguments.
Usage
quot(val1, val2)
Examples
${quot(10, 2)}
5.0
keyboard_arrow_rightkeyboard_arrow_downrint()
Returns a random integer value between 0 (inclusive) and the bound
parameter (exclusive).
Usage
rint(bound)
Notes
bound
must be numericbound
must be greater than 0
Examples
${rint(100)}
42
keyboard_arrow_rightkeyboard_arrow_downround()
Returns the given value, rounded to the nearest integer. This method tries to convert its parameter objects into numerical values, i.e. you can use strings as arguments. If the optional parameter decimalPlaces
is given, this method rounds to the given number of decimal places.
Usage
round(val [, decimalPlaces ])
Examples
(1) ${round(5.876543, 2)}
(2) ${round(5.49)}
(3) ${round(5.5)}
(1) 5.88
(2) 5
(3) 6
keyboard_arrow_rightkeyboard_arrow_downsubt()
Returns the subtraction result of val1 minus val2. This method tries to convert its parameter objects into numerical values, i.e. you can use strings as arguments.
Usage
subt(val1, val2)
Examples
${subt(5, 2)}
3.0
keyboard_arrow_rightkeyboard_arrow_downunarchive()
Unarchives given file to an optional parent folder.
Usage
${unarchive(archiveFile [, parentFolder])}
${{$.unarchive(archiveFile [, parentFolder])}}
Notes
The unarchive() function takes two parameter. The first parameter is a file object that is linked to an archive file, the second (optional) parameter points to an existing parent folder. If no parent folder is given, a new subfolder with the same name as the archive (without extension) is created. The supported file types are ar, arj, cpio, dump, jar, tar, zip and 7z.
Examples
${unarchive(first(find('File', 'name', 'archive.zip')), first(find('Folder', 'name', 'parent')) )}
${{ $.unarchive($.first($.find('File', 'name', 'archive.zip')), $.first($.find('Folder', 'name', 'parent')) )}}
Query Functions
keyboard_arrow_rightkeyboard_arrow_downAdvanced find()
This method is one of the most important and frequently used built-in functions. It returns a collection of entities, which can be empty if none of the existing nodes or relationships matches the given search parameters.
find()
accepts several different predicates (key, value pairs) and other query options like sort order or pagination controls. See the examples below for an overview of the possible parameter combinations for an advanced find() query. The simpler usage of the find()
function is documented below in the article for find()
Predicates
The following predicates can be specified. Predicates can be combined and mixed to build complex queries. Some predicates and property keys need to be combined in a different way than others, please refer to the examples below for an overview.
Predicate | Description |
---|---|
and(...) | Logical AND |
or(...) | Logical OR |
not(...) | Logical NOT |
equals(key, value) | Returns only those nodes that match the given (key, value) pair |
contains(key, text) | Returns only those nodes whose value contains the given text |
empty('key') | Returns only those nodes that don’t have a value set for the given key |
range(start, end [, withStart = true [, withEnd = true ]] ) | Returns only those nodes where the given propertyKey is in the range between start and end |
range(null, end) | Unbounded range() to emulate “less than” |
range(start, null) | Unbounded range() to emulate “greater than” |
starts_with(key, prefix) | Returns only those nodes whose value for the given key starts with the given prefix |
ends_with(key, suffix) | Returns only those nodes whose value for the given key ends with the given suffix |
within_distance(latitude, longitude, distance) | Returns only those nodes that are within distance meters around the given coordinates. The type that is being searched for needs to extend the built-in type Location |
Options
The following options can be specified:
Option | Description |
---|---|
sort(key) | Sorts the result according to the given property key (ascending) |
sort(key, true) | Sorts the result according to the given property key (descending) |
page(page, pageSize) | Limits the result size to pageSize , returning the given page |
Usage
find(type, predicates..., options...)
Notes
Predicates at root level are combined as logical AND clauses.
For information about the regular usage of the find() function please see the article below.
Examples
StructrScript
-------------
(1) ${find('User', sort('name'))}
(2) ${find('User', sort('name'), page(1, 10))}
(3) ${find('User', contains('name', 'e'))}
(4) ${find('User', 'age', range(0, 18))}
(5) ${find('User', 'age', range(0, 18, false, false))}
(6a) ${find('User', equals('name', 'Tester'), equals('age', range(0, 18)))}
(6b) ${find('User', and(equals('name', 'Tester'), equals('age', range(0, 18))))}
(7) ${find('BakeryLocation', and(within_distance(48.858211, 2.294507, 1000)))}
JavaScript (up until Structr 3.6.x)
-----------------------------------
(8)
${{
$.find('User', $.sort('name'), $.page(1, 10))
}}
(9)
${{
let users = $.find('Project',
{
$and: {
'name': 'structr',
'age': $.range(30, 50)
}
},
$.sort('name', true),
$.page(1, 10)
);
return users;
}}
(10)
${{
// Showcasing the *limitation* of the MAP SYNTAX: OR on the same property is not possible. See 13b for a solution
let users = $.find('User',
{
$or: {
'name': 'jeff',
'name': 'joe'
}
}
);
return users;
}}
JavaScript (Structr 4.0 and up)
-----------------------------------
(11)
${{
$.find('User', $.predicate.sort('name'), $.predicate.page(1, 10))
}}
(12)
${{
let users = $.find('Project',
{
$and: {
'name': 'structr',
'age': $.predicate.range(30, 50)
}
},
$.predicate.sort('name', true),
$.predicate.page(1, 10)
);
return users;
}}
(13a)
${{
// Showcasing the *limitation* of the MAP SYNTAX: OR on the same property is not possible. See 13b for a solution
let users = $.find('User',
{
$or: {
'name': 'jeff',
'name': 'joe'
}
}
);
return users;
}}
(13b)
${{
// Showcasing the *advantage* of the PREDICATE SYNTAX: OR on the same property is possible. See (13c) for a more elegant version
let users = $.find(
'User',
$.predicate.or(
$.predicate.equals('name', 'jeff'),
$.predicate.equals('name', 'joe')
)
);
return users;
}}
(13c)
${{
// More advanced example where predicates are created before of the query
let nameConditions = [
$.predicate.equals('name', 'jeff'),
$.predicate.equals('name', 'joe')
];
let users = $.find('User', $.predicate.or(nameConditions));
return users;
}}
(13d)
${{
// More advanced example where predicates are created before of the query.
let nameConditions = [
$.predicate.equals('name', 'jeff'),
$.predicate.equals('name', 'joe')
];
let rootPredicate = $.predicate.and(
$.predicate.equal('isAdmin', true),
$.predicate.or(nameConditions)
);
let users = $.find('User', rootPredicate);
return users;
}}
StructrScript
-------------
(1) returns all User entities in the database, sorted by name
(2) returns the first 10 User entities in the database, sorted by name
(3a + 3b) returns all user entities whose name property contains the letter 'e' (showcases the different ways to use the contains predicate)
(4) returns all user entities whose age property is between 0 and 18 (inclusive)
(5) returns all user entities whose age property is between 0 and 18 (exclusive)
(6a + 6b) returns all user entities whose name is 'Tester' and whose age is between 0 and 18 (inclusive). Showcases the implicit (6a) and explicit (6b) logical AND conjunction of root clauses
(7) Returns all bakeries (type BakeryLocation extends Location) within 1000 meters around the Eiffel Tower
JavaScript (up until Structr 3.6.x)
-----------------------------------
(8) returns the first 10 User entities in the database, sorted by name
(9) returns the first 10 projects (sorted descending by name) where 'name' equals 'structr' and the 'age' is between 30 and 50 (inclusive)
(10) Only the user "joe" will be returned because the map key "name" is used twice (which is impossible)
JavaScript (Structr 4.0 and up)
-------------------------------
(11) returns the first 10 User entities in the database, sorted by name
(12) returns the first 10 projects (sorted descending by name) where 'name' equals 'structr' and the 'age' is between 30 and 50 (inclusive)
(13a) Only the user "joe" will be returned because the map key "name" is used twice (which is impossible)
(13b) All users named "joe" or "jeff" will be returned
(13c) All users named "joe" or "jeff" will be returned. This showcases how to create condition predicates before adding them to the query
(13d) All users with the "isAdmin" flag set to true and named "joe" or "jeff" will be returned. This showcases how to create the complete predicate before the query
keyboard_arrow_rightkeyboard_arrow_downcypher()
Executes the given Cypher query and returns the results. Structr will automatically convert all query results into the corresponding Structr objects, i.e. Neo4j nodes will be instantiated to Structr node entities, Neo4j relationships will be instantiated to Structr relationship entities, and maps will converted into Structr maps that can be accessed using the dot notation (map.entry.subentry
).
Usage
cypher(query [, key1, value1 [, ... ]] )
cypher(query [, map] )
Notes
The
cypher()
function always returns a collection of objects, even ifLIMIT 1
is specified!In a StructrScript environment parameters are passed as pairs of
'key1', 'value1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
Examples
${cypher('MATCH (n:User) RETURN n')}
[7379af469cd645aebe1a3f8d52b105bd, a05c044697d648aefe3ae4589af305bd, 505d0d469cd645aebe1a3f8d52b105bd]
**Example using Parameters**
${{
let query = "MATCH (user:User) WHERE user.name = $userName RETURN user";
let users = $.cypher(query, {userName: 'admin'});
}}
keyboard_arrow_rightkeyboard_arrow_downfind()
This method is one of the most important and frequently used built-in functions. It returns a collection of entities, which can be empty if none of the existing nodes or relationships matches the given search parameters.
find()
accepts several different parameter combinations, whereas the first parameter is always the name of the type to retrieve from the database. The second parameter can either be a UUID (string), a map (e.g. a result from nested function calls) or a list of (key, value) pairs.
The given query parameters are combined with an AND predicate. For node attributes an exact match is searched for the given value. For remote attribute collections the given search values are combined with an OR predicate (see examples).
Usage
find(type [, key1, value1 [, ... ]] )
find(type [, map ])
find(type [, uuid ])
Notes
In a StructrScript environment parameters are passed as pairs of ‘key1’, ‘value1’.
In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
The
find()
method will always use exact search, if you are interested in inexact / case-insensitive search, usesearch()
.Calling
find()
with only a single parameter will return all the nodes of the given type (which might be problematic if there are so many of them in the database so that they do not fit in the available memory).
Examples
(1) ${find('User')}
(2) ${find('User', 'name', 'admin')}
(3) ${find('User', '7379af469cd645aebe1a3f8d52b105bd')}
(4) ${{
let alice = $.find('User', 'name', 'alice')[0];
let bob = $.find('User', 'name', 'bob')[0];
let userWithFriendAliceOrBob = $.find('User', {
hasFriends: [ alice, bob ]
});
}}
(1) [7379af469cd645aebe1a3f8d52b105bd, a05c044697d648aefe3ae4589af305bd, 505d0d469cd645aebe1a3f8d52b105bd]
(2) [7379af469cd645aebe1a3f8d52b105bd]
(3) This is a special case - a UUID was supplied, therefore only a single object is returned instead of a collection
(3) 7379af469cd645aebe1a3f8d52b105bd
(4) // returns every user who is friends with either alice or bob
keyboard_arrow_rightkeyboard_arrow_downfind_privileged()
Executes a find() operation with elevated privileges.
Usecases
find_privileged()
can be used to query data from an anonymous context or when a users privileges need to be escalated.
Usage
find_privileged(type [, key1, value1 [, ... ]] )
find_privileged(type [, map ])
find_privileged(type [, uuid ])
find_privileged(type)
Notes
It is recommended to use find() instead of find_privileged() whenever possible, as improper use of find_privileged() can result in the exposure of sensitive data.
In a StructrScript environment parameters are passed as pairs of ‘key1’, ‘value1’.
In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
keyboard_arrow_rightkeyboard_arrow_downfind_relationship()
Returns a collection of entities of the given type from the database, takes optional key/value pairs
Usage
find_relationship(type [, key1, value1, [, ...] ])
find_relationship(type [, map ])
Notes
The relationship type for custom schema relationships is auto-generated as
<source type name><relationship type><target type name>
In a StructrScript environment parameters are passed as pairs of
'key1', 'value1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
Examples
${find_relationship("PersonRELATED_TOPerson")}
${find_relationship("ProjectCONTAINSTask")}
keyboard_arrow_rightkeyboard_arrow_downget_or_create()
get_or_create()
finds and returns a single object with the given properties (key/value pairs or a map of properties) and creates that object if it does not exist yet.
The function accepts three different parameter combinations, where the first parameter is always the name of the type to retrieve from the database. The second parameter can either be a map (e.g. a result from nested function calls) or a list of (key, value) pairs.
Usage
get_or_create(type [, key1, value1, [, ...] ])
get_or_create(type [, map ])
Notes
The
get_or_create()
method will always use exact search, if you are interested in inexact / case-insensitive search, usesearch()
.In a StructrScript environment parameters are passed as pairs of
'key1', 'value1'
.In a JavaScript environment, the function can be used just as in a StructrScript environment. Alternatively it can take a map as the second parameter.
Examples
${get_or_create('User', 'name', 'admin')}
${get_or_create('User', 'name', 'admin')}
${get_or_create('User', 'name', 'admin')}
7379af469cd645aebe1a3f8d52b105bd
7379af469cd645aebe1a3f8d52b105bd
7379af469cd645aebe1a3f8d52b105bd
The example shows that repeated calls to `get_or_create()` with the same parameters will always return the same object.
keyboard_arrow_rightkeyboard_arrow_downrange()
Returns a search predicate to specify value ranges, greater and less-than searches in find() and search() functions. The first two parameters represent the first and the last element of the desired query range. Both start and end of the range can be set to null
to allow the use of range()
for <
, <=
. >
and >=
queries.
There are two optional boolean parameters, includeStart
and includeEnd
that control whether the search range should include or exclude the endpoints of the interval.
Usage
range(start, end)
range(start, end, includeStart, includeEnd)
Examples
${find('Project', 'taskCount', range(0, 10))}
${find('Project', 'taskCount', range(0, 10, true, false))}
${find('Project', 'taskCount', range(0, 10, false, false))}
**Server-side JavaScript Examples**
Structr.find('Project').forEach(p => Structr.print(p.index + ", "));
=> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Structr.find('Project', { index: Structr.range(2, 5) }).forEach(p => Structr.print(p.index + ", "));
=> 2, 3, 4, 5,
Structr.find('Project', { index: Structr.range(2, 5, false) }).forEach(p => Structr.print(p.index + ", "));
=> 3, 4, 5,
Structr.find('Project', { index: Structr.range(2, 5, false, false) }).forEach(p => Structr.print(p.index + ", "));
=> 3, 4,
keyboard_arrow_rightkeyboard_arrow_downsearch()
The search()
method is very similar to find()
, except that it is case-insensitive / inexact. It returns a collection of entities, which can be empty if none of the existing nodes or relationships matches the given search parameters.
search()
accepts several different parameter combinations, whereas the first parameter is always the name of the type to retrieve from the database. The second parameter can either be a map (e.g. a result from nested function calls) or a list of (key, value) pairs. Calling search()
with only a single parameter will return all the nodes of the given type (which might be dangerous if there are many of them in the database).
Usage
search(type [, key1, value1 [, ... ]] )
search(type [, map ])
search(type [, uuid ])
search(type)
Examples
For this example, we assume that there are three users in the database: [admin, tester1, tester2].
${search('User')}
${search('User', 'name', 'test')}
[7379af469cd645aebe1a3f8d52b105bd, a05c044697d648aefe3ae4589af305bd, 505d0d469cd645aebe1a3f8d52b105bd]
[a05c044697d648aefe3ae4589af305bd, 505d0d469cd645aebe1a3f8d52b105bd]
keyboard_arrow_rightkeyboard_arrow_downxpath()
Returns the value of the given XPath expression from the given XML DOM. The optional third parameter defines the return type, possible values are: NUMBER, STRING, BOOLEAN, NODESET, NODE, default is STRING. This method can be used in conjunction with xml()
and read()
to read an XML file from the Structr exchange/
directory. Alternatively a file from the virtual filesystem can be read using the get_content()
function. See Anatomy of a Structr application for more information.
Usage
xpath(xmlDocument, xpathExpression[, returnType])
Examples
xmlString is assumed to be
<xml>
<projects>
<project name='p1'>
<budget>100</budget>
</project>
<project name='p2'>
<budget>500</budget>
</project>
</projects>
</xml>
(1) ${xpath(xml(xmlString), "/xml/projects/project[1]/budget", "STRING")
(2) ${xpath(xml(xmlString), "/xml/projects/project[2]/budget", "STRING")
(3) ${xpath(xml(xmlString), "/xml/projects/project[2]/@name", "STRING")
(1) 100
(2) 500
(3) p2
Rendering Functions
keyboard_arrow_rightkeyboard_arrow_downget_counter()
Returns the counter value for the given level.
Usage
get_counter(level)
Notes
The level has to be numeric.
Examples
${get_counter(1)}
0
keyboard_arrow_rightkeyboard_arrow_downinc_counter()
Increases the counter value for the given level, optionally resetting the value of all counters below the given level with the second parameters, which accepts a boolean value.
Usage
inc_counter(level, resetLowerLevels)
inc_counter(level)
Notes
The level has to be numeric.
Examples
${inc_counter(1, true)}
<no output>
keyboard_arrow_rightkeyboard_arrow_downinclude()
Loads the element with the given name and renders its HTML representation into the output buffer. Nodes can be included via their name
property. When used with an optional collection and data key argument, the included HTML element will be renderd as a Repeater Element.
Possible nodes MUST:
1. have a unique name
2. NOT be in the trash
Possible nodes CAN:
1. be somewhere in the pages tree
2. be in the Shared Components
Together with render()
, include()
is one of the most important methods when dealing with HTML web templates since it allows the user to populate static HTML pages with dynamic content from the underlying node structure.
Usage
include(name)
include(name, collection, dataKey)
Examples
${include('Main Menu')}
will render the contents of the [Shared Component](/article/Shared%20Components) with the name "Main Menu" into the output buffer.
${include('Item Template', find('Item'), 'item')}
will render the contents of the [Shared Component](/article/Shared%20Components) with the name "Item Template" repeatedly for every Item node in the database.
keyboard_arrow_rightkeyboard_arrow_downinclude_child()
Loads a template’s child element with the given name and renders its HTML representation into the output buffer. Nodes can be included via their name
property. When used with an optional collection and data key argument, the included HTML element will be renderd as a Repeater Element.
Together with render()
and include()
, include_child()
is one of the most important methods when dealing with HTML web templates since it allows the user to populate static HTML pages with dynamic content from the underlying node structure. See Page Rendering for more information on this topic.
Usage
include_child(name)
include_child(name, collection, dataKey)
Notes
Works only during page rendering in Template nodes!
Child nodes must be direct children of the template node
Underneath the template node, child node names MUST be unique in order for include_child() to work
Examples
(1) ${include_child('Child Node')}
(2) ${include_child('Item Template', find('Item'), 'item')}
(1) will render the contents of the child node with the name "Child Node" into the output buffer.
(2) will render the contents of the child node with the name "Item Template" repeatedly for every Item node in the database.
keyboard_arrow_rightkeyboard_arrow_downprint()
Prints the string representation of all of the given objects into the page rendering buffer. This method is often used in conjunction with each()
to create rendering output for a collection of entities etc. in scripting context.
Usage
print(objects...)
Examples
${print('Hello, world!')}
Hello, world!
keyboard_arrow_rightkeyboard_arrow_downrender()
Renders the HTML representation of the given node(s) into the output buffer. This method is exactly equivalent to the rendering process that Structr uses internally to create the HTML output of pages etc. It can be used to render dynamic content in pages with placeholders etc.
Together with include()
, render()
is one of the the most important method when dealing with HTML web templates, since it allows the user to fill static HTML pages with dynamic content from the underlying node structure. See Page Rendering for more information on this topic.
Usage
render(nodes)
render(node)
Examples
${render(children)}
keyboard_arrow_rightkeyboard_arrow_downreset_counter()
Resets the counter for the given level.
Usage
reset_counter(level)
Notes
The level has to be numeric.
Examples
${reset_counter(1)}
<no output>
keyboard_arrow_rightkeyboard_arrow_downset_details_object()
Allows overriding the current
keyword with a given entity.
Usage
set_details_object(entity)
Examples
${set_details_object(first(find('User')))}
Schema Functions
keyboard_arrow_rightkeyboard_arrow_downancestor_types()
Returns the list of parent types of the given type including the type itself. Additionally a blacklist of type names can be provided as a list. If omitted, the list contains only “AbstractNode” by default.
Usage
ancestor_types(type[, blacklist])
Examples
${ancestor_types("MyType")}
${ancestor_types("MyType", merge())} (merge() is used to create an empty list so the blacklist is reset)
[MyType]
[MyType, AbstractNode]
keyboard_arrow_rightkeyboard_arrow_downenum_info()
Returns a list of the possible values of an enum property.
If the rawList
flag is set to “true”, a simple list will be returned. If it is omitted or set to false, a list of objects will be returned (so it can be used in a repeater element)
Usage
enum_info(typeName, enumName [, rawList = false])
Examples
An enum property `words` is defined on the type `Doge` with format = "such, choices, much, awesome"
(1) ${enum_info("Doge", "words")}
(2) ${enum_info("Doge", "words", true)}
(1) [{value: "such"}, {value: "choices"}, {value: "much"}, {value: "awesome"}]
(2) ["such", "choices", "much", "awesome"]
keyboard_arrow_rightkeyboard_arrow_downinheriting_types()
Returns the list of inheriting types of the given type including the type itself. Additionally a blacklist of type names can be provided as a list. If omitted, the blacklist is empty.
Usage
inheriting_types(type[, blacklist])
Examples
${inheriting_types("MyType")}
${inheriting_types("MyType", merge("UndesiredSubtype"))}
[MyType, Subtype1, Subtype2, UndesiredSubtype]
[MyType, Subtype1, Subtype2]
keyboard_arrow_rightkeyboard_arrow_downproperty_info()
Returns a property info object for the property of the given type with the given name. A property info object has the following structure:
Field | Description | Type |
---|---|---|
dbName | Database (Neo4j) name - can be used in Cypher etc. | String |
jsonName | JSON name (as it appears in JSON REST output) | String |
className | Class name of the property type | String |
declaringClass | Name of the declaring class | String |
defaultValue | Default value or null | String |
contentType | Content type or null (String only) | String |
format | Format or null | String |
readOnly | Read-only flag | Boolean |
system | System flag | Boolean |
indexed | Indexed flag | Boolean |
indexedWhenEmpty | Indexed-when-empty flag | Boolean |
unique | Unique flag | Boolean |
notNull | Not-null flag | Boolean |
dynamic | Dynamic flag | Boolean |
relatedType | Related type (for relationship properties) | String |
type | Property type from definition | String |
uiType | Extended property type for Edit Mode (e.g. String, String[] etc.) | String |
isCollection | Collection or entity (optional) | String |
databaseConverter | Database converter type (internal) | String |
inputConverter | Input converter type (internal) | String |
relationshipType | Relationship type (for relationship properties) | String |
Usage
property_info(type, name)
Examples
${property_info('User', 'name').uiType}
String
keyboard_arrow_rightkeyboard_arrow_downtype_info()
If called with a view, all properties of that view are returned as a list. The items of the list are in the same format as property_info()
returns. This is identical to the result one would get from /structr/rest/_schema/<type>/<view>
.
If called without a view, the complete type information is returned as an object. This is identical to the result one would get from /structr/rest/_schema/<type>
.
Usage
type_info(type[, view])
String Functions
keyboard_arrow_rightkeyboard_arrow_downabbr()
Abbreviates the given string at the last space character before the maximum length is reached.
The remaining characters are replaced with the ellipsis character (…) or the given abbr
parameter.
Usage
abbr(string, maxLength [, abbr = '…' ] )
Examples
${abbr('A long string that is too long to be displayed entirely.', 20)}
A long string that…
keyboard_arrow_rightkeyboard_arrow_downbase64decode()
Decodes the given base64 text using the supplied scheme. Valid values for scheme
are basic
(default), url
and mime
.
The following explanation of the encoding schemes is taken directly from https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html
Basic
Uses “The Base64 Alphabet” as specified in Table 1 of RFC 4648 and RFC 2045 for encoding and decoding operation. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
URL and Filename safe
Uses the “URL and Filename safe Base64 Alphabet” as specified in Table 2 of RFC 4648 for encoding and decoding. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
MIME
Uses the “The Base64 Alphabet” as specified in Table 1 of RFC 2045 for encoding and decoding operation. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return ‘\r’ followed immediately by a linefeed ‘\n’ as the line separator. No line separator is added to the end of the encoded output. All line separators or other characters not found in the base64 alphabet table are ignored in decoding operation.
Usage
base64decode(text,[ scheme = basic [, charset]])
Examples
${base64decode("Q2hlY2sgb3V0IGh0dHA6Ly9zdHJ1Y3RyLmNvbQ==")}
Check out http://structr.com
keyboard_arrow_rightkeyboard_arrow_downbase64encode()
Encodes the given string in base64 using the supplied scheme. Valid values for scheme
are basic
(default), url
and mime
.
The following explanation of the encoding schemes is taken directly from https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html
Basic
Uses “The Base64 Alphabet” as specified in Table 1 of RFC 4648 and RFC 2045 for encoding and decoding operation. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
URL and Filename safe
Uses the “URL and Filename safe Base64 Alphabet” as specified in Table 2 of RFC 4648 for encoding and decoding. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
MIME
Uses the “The Base64 Alphabet” as specified in Table 1 of RFC 2045 for encoding and decoding operation. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return ‘\r’ followed immediately by a linefeed ‘\n’ as the line separator. No line separator is added to the end of the encoded output. All line separators or other characters not found in the base64 alphabet table are ignored in decoding operation.
Usage
base64encode(text,[ scheme = basic [, charset]])
Examples
${base64encode("Check out http://structr.com")}
Q2hlY2sgb3V0IGh0dHA6Ly9zdHJ1Y3RyLmNvbQ==
keyboard_arrow_rightkeyboard_arrow_downcapitalize()
Capitalizes a String changing the first character to title case. No other characters are changed. If the first character has no explicit titlecase mapping and is not itself a titlecase char according to UnicodeData, then the uppercase mapping is returned as an equivalent titlecase mapping.
Usage
capitalize(string)
Examples
(1) ${capitalize("cat dog bird")}
(2) ${capitalize("cAT DOG BIRD")}
(3) ${capitalize("'cat dog bird'")}
(1) "Cat dog bird"
(2) "CAT DOG BIRD"
(3) "'cat dog bird'"
keyboard_arrow_rightkeyboard_arrow_downclean()
This method can be used to convert complex strings or collections of strings (e.g. user names, article titles, etc.) into simple strings that can be used in URLs etc.
Characters | Action |
---|---|
Whitespace | Replace with - (consecutive whitespaces are replaced with a single - ) |
–'+/|\ | Replace with - |
Uppercase letters | Replace with corresponding lowercase letter |
<>.?(){}[]!, | Remove |
Usage
clean(string)
clean(collection)
Notes
Strings are normalized in the NFD form (see. http://www.unicode.org/reports/tr15/tr15-23.html) before the replacements are applied.
Examples
(1) ${clean('This is Än example')}
(2) ${clean(merge('This is Än example', 'This is Änother example'))}
(1) this-is-an-example
(2) ['this-is-an-example', 'this-is-another-example']
keyboard_arrow_rightkeyboard_arrow_downcoalesce()
Returns the first non-null value in the list of expressions passed to it. In case all arguments are null, null will be returned.
Usage
coalesce(node.name, node.title, node.id, ...)
Examples
(1) ${coalesce(null, null, 'cat', 'dog', 'bird')}
(2) ${coalesce(null, '', 'cat', 'dog', 'bird')}
(1) 'cat'
(2) ''
keyboard_arrow_rightkeyboard_arrow_downconcat()
Concatenates the given list of objects into a single string without a separator between them.
The objects can be of any type: string, number, entity, collection. If a collection is encountered, all elements of that collection are concatenated.
Usage
concat(object...)
Notes
null
values are filtered and not concatenated
Examples
(1) ${concat('test', 1, me, ' a string')}
(2) ${concat('test ', merge('con', 'cat', 'enate'), ' ', me.name)}
(1) test1.0d8915af2c66942aeb46b960349fcadbc a string
(2) test concatenate admin
keyboard_arrow_rightkeyboard_arrow_downcontains()
Returns a boolean value that indicates whether the given string contains the given word or the given collection contains the given element.
Usage
contains(string, word)
contains(collection, element)
Examples
${contains('This is a test string', 'test')}
${contains(find('Page'), page)}
true
keyboard_arrow_rightkeyboard_arrow_downends_with()
Predicate function - returns true if the given string ends with the given suffix.
Usage
ends_with(string, suffix)
Examples
(1) ${ends_with('Hello World!', 'World!')}
(2) ${ends_with('Hello World!', 'Mundo!')}
(1) true
(2) false
keyboard_arrow_rightkeyboard_arrow_downescape_html()
Replaces special characters in text with their HTML entities, e.g. &
with &
.
Supports all known HTML 4.0 entities, including funky accents.
Usage
escape_html(string)
Notes
Note that the commonly used apostrophe escape character (’) is not a legal entity and so is not supported.
Examples
${escape_html('Test & Test"')}
Test & Test"
keyboard_arrow_rightkeyboard_arrow_downescape_javascript()
Escapes the given string for use in Javascript.
Usage
escape_javascript(string)
Notes
Escapes the characters in a string using EcmaScript String rules.
Escapes any values it finds into their EcmaScript String form.
Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.).
Examples
${escape_javascript('This is a "test"')}
This is a \"test\"
keyboard_arrow_rightkeyboard_arrow_downescape_json()
Escapes the given string for use in JSON.
Usage
escape_json(string)
Notes
Escapes the characters in a string using Json String rules.
Escapes any values it finds into their Json String form.
Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.)
Examples
${escape_json('This is a "test"')}
This is a \"test\"
keyboard_arrow_rightkeyboard_arrow_downescape_xml()
Escapes the characters in a String using XML entities.
Usage
escape_xml(string)
Notes
Supports only the five basic XML entities (gt, lt, quot, amp, apos).
Does not support DTDs or external entities.
Unicode characters greater than 0x7f are currently escaped to their numerical \u equivalent. This may change in future releases.
Examples
${escape_xml('This is a "test" & another "test"')}
This is a "test" & another "test"
keyboard_arrow_rightkeyboard_arrow_downformurlencode()
Encodes the given object for use in an URL, replacing invalid characters with their valid URL equivalent and joining the key/value pairs with an ampersand.
Usage
formurlencode(object)
Notes
This function is best used in a JavaScript context
Examples
(1) $.formurlencode({name:"admin", p1: 12, apiKey: "abc123", text:"Text with umläut"})
(2) $.formurlencode({name:"admin", p1: 12, apiKey: "abc123", text:"Text with umläut", sub: { subKey1: "subValue1", subKey2: 42 }})
(1) name=admin&p1=12&apiKey=abc123&text=Text+with+uml%C3%A4ut
(2) name=admin&p1=12&apiKey=abc123&text=Text+with+uml%C3%A4ut&sub[subKey1]=subValue1&sub[subKey2]=42
keyboard_arrow_rightkeyboard_arrow_downfrom_csv()
Parses the given source string and returns an object representation of the string.
If the parameter headerList
is not supplied, it is assumed that the first line of the CSV is a header and those header values are used as property names.
If the parameter is supplied, the given values are used as property names and the first line is read as data.
Usage
from_csv(source[, delimiter = ';' [, quoteChar = '"' [, recordSeparator = '\n' [, headerList ] ]]])
Examples
(1) ${from_csv('COL1;COL2;COL3\nline1:one;line1:two;line1:three\nline2:one;line2:two;line2:three')}
(2) ${first(from_csv('COL1;COL2;COL3\nline1:one;line1:two;line1:three\nline2:one;line2:two;line2:three')).COL2}
(3) ${from_csv('COL1;COL2;COL3\nline1:one;line1:two;line1:three\nline2:one;line2:two;line2:three', ';', '"', '\n', merge('a', 'b', 'c') )}
(1) [{COL1=line1:one, COL2=line1:two, COL3=line1:three}, {COL1=line2:one, COL2=line2:two, COL3=line2:three}]
(2) line1:two
(3) [{a=COL1, b=COL2, c=COL3}, {a=line1:one, b=line1:two, c=line1:three}, {a=line2:one, b=line2:two, c=line2:three}]
keyboard_arrow_rightkeyboard_arrow_downfrom_json()
Parses the given source string and returns a Structr object representation of the string. This method is the inverse of to_json()
.
Usage
from_json(source)
Notes
In a JavaScript scripting context the
JSON.parse()
function is available.
Examples
(1) ${from_json('{name: Test, value: 123}')}
(2) ${from_json('{name: Test, value: 123}').name}
(1) {name=Test, value=123.0}
(2) Test
keyboard_arrow_rightkeyboard_arrow_downfrom_xml()
Parses the given XML and returns a JSON representation of the XML which can be further processed using from_json()
or JSON.parse()
.
Usage
from_xml(source)
Examples
${from_xml('<entry>0</entry>')}
{"entry": 0}
keyboard_arrow_rightkeyboard_arrow_downget_csv_headers()
Parses the given CSV string and returns a list of column headers
Usage
get_csv_headers(source[, delimiter = ';' [, quoteChar = '"' [, recordSeparator = '\n' ]]])
Examples
${get_csv_headers('COL1;COL2;COL3\none;two;three')}
["COL1", "COL2", "COL3"]
keyboard_arrow_rightkeyboard_arrow_downhash()
Returns the hash (as a hexadecimal string) of a given string, using the given algorithm (if available via the underlying JVM).
Currently, the SUN provider makes the following hashes/digests available: MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, SHA-512/256, SHA3-224, SHA3-256, SHA3-384, SHA3-512
If an algorithm does not exist, an error message with all available algorithms will be logged and a null value will be returned.
Usage
hash(algorithm, value)
Notes
Available in v5.0
Examples
hash('SHA-512', 'Hello World!')
861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8
keyboard_arrow_rightkeyboard_arrow_downindex_of()
Returns the position of the first occurrence of the given word in the given string, or -1 if the string doesn’t contain the word.
Usage
index_of(string, word)
Examples
${index_of('This is a test', 'test')}
10
keyboard_arrow_rightkeyboard_arrow_downjoin()
Joins the given collection of strings into a single string, separated by the given separator. This method is often used in conjunction with find()
and extract()
to create comma-separated lists of entity names etc. The merge()
function can be used to create a list of strings like in the following example.
Usage
join(collection, separator)
Examples
(1) ${join(merge('one', 'two', 'three'), ', ')}
(2) ${join(extract(find('User'), 'name'), ', ')}
(1) one, two, three
(2) admin, tester1, tester2, tester3
keyboard_arrow_rightkeyboard_arrow_downlength()
Returns the length of the given string.
Usage
length(string)
Examples
${length('This is a test')}
14
keyboard_arrow_rightkeyboard_arrow_downlocalize()
The localize() function can be used to localize strings and therefor create localized user interfaces. It uses the current locale
(see keyword locale) to search for nodes of type Localization
in the database. This lookup works in 4 stages. If a Localization object is found (in the order of evaluation), the process is stopped. If no localization is found, the key
itself is returned.
- find localization with exact match on key, domain and full locale
- find localization with exact match on key, NO domain and full locale
- find localization with exact match on key, domain and language only
- find localization with exact match on key, domain and language only
- Restart steps 1-4 with the fallback locale - if defined and active via structr.conf:
application.localization.usefallbacklocale
= enable/disable use of the fallback localeapplication.localization.fallbacklocale
= the fallback locale
If after step 4 no localization is found, the input parameters are logged if the configuration entry application.localization.logmissing
in structr.conf is enabled.
Usage
localize(key [, domain])
localize(keys [, domain])
Examples
<input type="text" placeholder="${localize('username')}...">
// if the current locale is en_US
<input type="text" placeholder="Username...">
// if the current locale is de_DE
<input type="text" placeholder="Benutzername...">
keyboard_arrow_rightkeyboard_arrow_downlower()
Returns the lowercase value of the given string.
Usage
lower(string)
Examples
${lower('STRUCTR')}
structr
keyboard_arrow_rightkeyboard_arrow_downmd5()
Returns the MD5 hash value (32 characters alphanumeric (hex)) of the given string. The method takes exactly one argument.
Usage
md5(string)
Examples
<div id="user-${md5(me.name)}"></div>
<div id="user-c3bfefa0c01486e95cc345472626e9cb)}"></div>
keyboard_arrow_rightkeyboard_arrow_downnumber_format()
Formats the given number in the given language according to the given pattern. This method uses the Java NumberFormat class which supports the ISO two-letter language codes, e.g. “en”, “de” etc. The following four pattern chars are supported:
Letter | Description |
---|---|
0 | Any number, or “0” |
# | Any number, or nothing |
. | The decimal separator |
, | The thousands-separator |
Usage
number_format(number, languageCode, pattern)
Examples
${number_format(1.234, 'en', '###0.0000')}
${number_format(1234567, 'de', '0,000,000.0000')}
1.2340
1.234.567,0000
keyboard_arrow_rightkeyboard_arrow_downparse_number()
Parses the given string into a numerical value. With the second (optional) parameter you can pass a locale string to take a country-/language specific number formatting into account.
Usage
parse_number(string[, locale])
Notes
If no locale parameter is given, the default locale for the context is used. See the
locale
keyword.
Examples
(1) ${parse_number('123,456,789.123', 'en')}
(2) ${parse_number('123.456.789,123', 'de')}
(1) 123456789.123
(2) 123456789.123
keyboard_arrow_rightkeyboard_arrow_downrandom()
Returns a random alphanumerical string of the given length. This method can for example be used to create default passwords etc.
Usage
random(length)
Examples
${random(8)}
gz5sl4z
keyboard_arrow_rightkeyboard_arrow_downreplace()
Replaces all template expressions in the given template string with values from the given entity. This method can be used to evaluate template expressions in database objects, for example to create customized e-mails etc.
Usage
replace(template, entity)
Notes
Allowing user input to be evaluated in a template expression poses a security risk. You have no control over what the user can do!
Examples
${replace('Welcome, ${this.name}!', me)}
Welcome, admin!
keyboard_arrow_rightkeyboard_arrow_downsplit()
Uses the given separator to split the given string into a collection of strings. This is the opposite of join()
.
The default separator is a regular expression which splits the string at ANY of the following characters: ,;(whitespace)
The optional second parameter is used as literal separator, it is NOT used as a regex. To use a regular expression to split a string, see split_regex().
Usage
split(string [, separator])
Notes
Adjacent separators are treated as one separator
Examples
${split('one,two,three,four')}
${split('one;two;three;four')}
${split('one two three four')}
${split('one::two::three::four', ':')}
${split('one.two.three.four', '.')}
${split('one,two;three four')}
[one, two, three, four]
keyboard_arrow_rightkeyboard_arrow_downsplit_regex()
Uses the given separator to split the given string into a collection of strings. This is the opposite of join()
.
The default separator is a regular expression which splits the string at any of the following characters: ,;(whitespace)
The optional second parameter is used as regex. To use a literal string as separator, see split().
Usage
split_regex(string, separator)
Examples
${split_regex('one,two,three,four')}
${split_regex('one;two;three;four')}
${split_regex('one two three four')}
${split_regex('one::two::three::four', ':+')}
${split_regex('one.two.three.four', '\\.')}
${split_regex('one:two&three%four', ':|&|%')}
[one, two, three, four]
keyboard_arrow_rightkeyboard_arrow_downstarts_with()
Predicate function - returns true if the given string starts with the given prefix.
Usage
starts_with(string, prefix)
Examples
(1) ${starts_with('Hello World!', 'Hello')}
(2) ${starts_with('Hello World!', 'Hola')}
(1) true
(2) false
keyboard_arrow_rightkeyboard_arrow_downstr_replace()
Replaces each substring of the subject that matches the given regular expression with the given replacement.
Usage
str_replace(subject, search, replacement)
Examples
${str_replace("Hello Wrlod!", "Wrlod", "World")}
Hello World!
keyboard_arrow_rightkeyboard_arrow_downstrip_html()
Removes all HTML tags from the given source string and returns only the content.
Usage
strip_html(source)
Notes
Similar results can be produced by
str_replace(source, "\\<[a-zA-Z].*?>", "")
Examples
${strip_html('<h3><p>Clean me!</p></h3>')}
Clean me!
keyboard_arrow_rightkeyboard_arrow_downsubstring()
Returns a portion with the given length of the given string, starting from the given start index. If no length parameter is given or the length would exceed the string length (calculated from the start index), the rest of the string is returned.
Usage
substring(string, start [, length ])
Examples
(1) ${substring('This is my test', 2)}
(2) ${substring('This is my test', 8, 2)}
(3) ${substring('This is my test', 8, 100)}
(1) is is my test
(2) my
(3) my test
keyboard_arrow_rightkeyboard_arrow_downtemplate()
Loads a node of type MailTemplate
with the given name and locale values and uses the given source entity to resolve template expressions in the content field of the loaded node, returning the resulting text.
Usage
template(name, locale, source)
Notes
This function is quite similar to the
replace()
function which serves a similar purpose but works on any string rather than on a mail template.The third parameter ‘source’ expects a node or relationship object fetched from the database. If the third parameter is an arbitrary design JavaScript object, it has to be wrapped with the
toGraphObject()
function, before being passed as the parameter.
Examples
// passing the Structr me object, representing the current user
${template('MAIL_SUBJECT', 'de', me)}
// passing an arbitrary JavaScript object
${{
return $.template('MAIL_SUBJECT', 'de', $.toGraphObject({name: "Mr. Foo"}))
}}
Assuming the MailTemplate is configured as:
Welcome, ${this.name}!
Welcome, admin!
keyboard_arrow_rightkeyboard_arrow_downtitleize()
Titleizes the given string. The given string is split at the separatorChars and each ‘word’ is titleized.
Usage
titleize(string[, separatorChars = " "])
Examples
(1) ${titleize('structr has a lot of built-in functions')}
(2) ${titleize('structr has a lot of built-in functions', '- ')}
(1) Structr Has A Lot Of Built-in Functions
(2) Structr Has A Lot Of Built In Functions
keyboard_arrow_rightkeyboard_arrow_downtrim()
Removes any leading or trailing whitespace from the given object. If the object is a string, a trimmed version will be returned. If it is a collection, a collection of trimmed strings will be returned.
Usage
trim(object)
Notes
A space is defined as any character whose codepoint is less than or equal to
U+0020
(the space character).
Examples
${trim(' A text with lots of whitespace ')}
${trim(merge(' A text with lots of whitespace ', ' Another text with lots of whitespace '))}
A text with lots of whitespace
[A text with lots of whitespace, Another text with lots of whitespace]
keyboard_arrow_rightkeyboard_arrow_downunescape_html()
Reverses the effect of escape_html().
Usage
unescape_html(string)
Examples
${unescape_html('Test & Test"')}
Test & Test"
keyboard_arrow_rightkeyboard_arrow_downupper()
Returns the uppercase value of the given string.
Usage
upper(string)
Examples
${upper('structr')}
STRUCTR
keyboard_arrow_rightkeyboard_arrow_downurlencode()
Encodes the given string for use in an URL, replacing invalid characters with their valid URL equivalent.
Usage
urlencode(string)
Examples
${urlencode('This is a test')}
This+is+a+test
Date Functions
keyboard_arrow_rightkeyboard_arrow_downdate_add()
Adds the given parameters to the given date and returns the resulting date.
Usage
date_add(date, year[, month[, day[, hour[, minute[, second]]]]])
Examples
(1) ${date_add(to_date(1585504800000), 1)}
(2) ${date_add(to_date(1585504800000), 0, -1)}
(1) Mon Mar 29 20:00:00 CEST 2021
(2) Sat Feb 29 20:00:00 CET 2020
keyboard_arrow_rightkeyboard_arrow_downdate_format()
Formats the given date object according to the given pattern, using the current locale (language/country settings). This method uses the Java SimpleDateFormat class which provides the following pattern chars:
Letter | Date or Time Component |
---|---|
G | Era designator |
y | Year |
Y | Week year |
M | Month in year |
w | Week in year |
W | Week in month |
D | Day in year |
d | Day in month |
F | Day of week in month |
E | Day name in week |
u | Day number of week (1 = Monday, …, 7 = Sunday) |
a | AM/PM marker |
H | Hour in day (0-23) |
k | Hour in day (1-24) |
K | Hour in AM/PM (0-11) |
h | Hour in AM/PM (1-12) |
m | Minute in hour |
s | Second in minute |
S | Millisecond |
z | General time zone |
Z | RFC 822 time zone |
X | ISO 8601 time zone |
Each character can be repeated multiple times to control the output format.
Pattern | Description |
---|---|
d | prints one or two numbers (e.g. “1”, “5” or “20”) |
dd | prints two numbers (e.g. “01”, “05” or “20”) |
EEE | prints the shortened name of the weekday (e.g. “Mon”) |
EEEE | prints the long name of the weekday (e.g. “Monday”) |
Usage
date_format(date, pattern)
Notes
Some format options are locale-specific. See the
locale
keyword for information about locales.
Examples
(1) ${date_format(to_date(1585504800000), 'yyyy-MM-dd')}
(2) ${date_format(to_date(1585504800000), 'EEEE')}
(3) ${(set_locale('de'), date_format(to_date(1585504800000), 'EEEE'))}
(1) 2020-03-29
(2) Sunday
(3) Sonntag
keyboard_arrow_rightkeyboard_arrow_downparse_date()
Parses the given string according to the given pattern and returns a date object. This method is the inverse of date_format().
Usage
parse_date(string, pattern)
Examples
${parse_date('2015-12-12', 'yyyy-MM-dd')}
Sat Dec 12 00:00:00 CET 2015
keyboard_arrow_rightkeyboard_arrow_downto_date()
Converts the given number into a date object.
The number is interpreted as UNIX timestamp (milliseconds from Jan. 1, 1970).
Usage
to_date(number)
Examples
${to_date(1585504800000)}
Sun Mar 29 20:00:00 CEST 2020
Keyword Helper Functions
The following functions are helpers to access JavaScript-only keywords from StructrScript
keyboard_arrow_rightkeyboard_arrow_downapplication_store_delete()
Removes a stored value from the application level store.
Usage
application_store_delete(key)
Examples
application_store_delete("do_no_track")
keyboard_arrow_rightkeyboard_arrow_downapplication_store_get()
Retrieves a stored value from the application level store.
Usage
application_store_get(key)
Examples
application_store_get("do_no_track")
true
keyboard_arrow_rightkeyboard_arrow_downapplication_store_get_keys()
Lists all keys stored in the application level store.
Usage
application_store_get_keys()
Examples
application_store_get_keys()
['do_not_track', 'key1', 'key2', 'key3']
keyboard_arrow_rightkeyboard_arrow_downapplication_store_has()
Checks if a key is present in the application level store.
Usage
application_store_has(key)
Examples
application_store_has('do_not_track')
true
keyboard_arrow_rightkeyboard_arrow_downapplication_store_put()
Stores a value in the application level store.
Usage
application_store_put(key, value)
Examples
application_store_put("do_no_track", true)
keyboard_arrow_rightkeyboard_arrow_downrequest_store_delete()
Removes a stored value from the request level store.
Usage
request_store_delete(key)
Examples
request_store_delete('do_not_track')
keyboard_arrow_rightkeyboard_arrow_downrequest_store_get()
Retrieves a stored value from the request level store.
Usage
request_store_get(key)
Examples
request_store_get('do_not_track')
true
keyboard_arrow_rightkeyboard_arrow_downrequest_store_get_keys()
Lists all keys stored in the request level store.
Usage
request_store_get_keys()
Examples
request_store_get_keys()
['do_not_track', 'key1', 'key2', 'key3']
keyboard_arrow_rightkeyboard_arrow_downrequest_store_has()
Checks if a key is present in the request level store.
Usage
request_store_has(key)
Examples
request_store_has('do_not_track')
true
keyboard_arrow_rightkeyboard_arrow_downrequest_store_put()
Stores a value in the request level store.
Usage
request_store_put(key, value)
Examples
request_store_put("do_no_track", true)