Go to page content

Advanced Dispatch URL Matching

There is an almost-unknown-but-added-because-someone-needed-it feature of dispatch rules: regular expressions.


Some developers need very particular control of dispatch in order for their applications to function as they want them to.  This guide exists to provide experienced Zotonic users with additional tools to express particularly advanced dispatch rules using regular expressions.


WARNING: this is ONLY for Zotonic dispatch wizards!!!!

Readers are expected to understand how dispatch rules work and also how regular expression work.


Say you want to only accept numerical arguments as an id in:

{foo, ["foo", id], resource_foo, []} 

The you can use a dispatch rule with a regular expression test:

{foo, ["foo", {id, "^[0-9]+$"}], resource_foo, []} 

or you can specify http://erldocs.com/R14B02/stdlib/re.html?i=14&search=re:#run/3 some extra options:

{foo, ["foo", {id, "1?2?", [notempty]}], resource_foo, []}

(The id must contain a 1 or a 2, amongst any other characters)

When all else fails, there is another option when you are, really, really, desperate for a specific check.

You can call a module:

{foo, ["foo", {id, {foo_module, foo_check}}], resource_foo, []}

Though note that this is (currently) an extremely expensive operation. It is in one of the main bottle necks of Zotonic, the z_sites_dispatcher gen_server which handles the matching of all incoming requests for all sites in one single process.

When matching against "foo/bar", the module is called as:

foo_module:foo_check("bar", Context).


Check the Syntax

Load your dispatch file in from the EShell with file:consult/1 and see if it returns errors.

Dispatch Rules are Order-sensitive

Dispatch rules are processed top-to-bottom in the file.  Are any rules above your rule capturing the cases you are trying to match.  If so, move your rule up, but bear in mind that you don't want to break those rules either.

This page is part of the Zotonic documentation, which is licensed under the Apache License 2.0.