Navigation

Controllers are the Erlang modules which decide
what happens when a browser requests a page. Zotonic looks at the
dispatch rules that match the requested URL,
and if a dispatch rule matches, the controller that is named in the
dispatch rule is used to handle the request.

Say we have the following dispatch rule, handling http://localhost/example:

{example_url,["example"],controller_example,[]},

When hitting /example, the controller_example controller will be
initialized and various callback functions on the controller will be
called, according to the HTTP protocol flow.

Controllers are pretty self-documenting, thanks to the names of the
webmachine callback functions. For instance, when you define a
function resource_exists/2, it will be called to decide whether or
not the page should return a 404 page.

The simplest controller uses Zotonic’s controller_html_helper.hrl include to serve HTML:

To return the rendered output of a template file in the module’s
templates directory, use z_template:render/3:

-module(controller_example).-include_lib("controller_html_helper.hrl").html(Context)->% foo and bam will be available as template variables in mytemplate.tpl.Html=z_template:render("mytemplate.tpl",[{foo,'bar'},{bam,1234}],Context),z_context:output(Html,Context).

If you need more examples, mod_base contains many controllers,
implementing basic HTTP interaction but also redirects, websockets, et
cetera. The Controllers page lists all available controllers in
the Zotonic core.