Add an HTTP controller

Use controller_template when a dispatch rule only needs to render a template. Write a custom controller when the endpoint needs additional request processing or response behavior.

Use controller_template for a page that only renders a template. For a public, read-only plain-text endpoint, create src/controllers/controller_garden_hello.erl in the active Garden application:

-module(controller_garden_hello).
-export([content_types_provided/1, process/4]).

-spec content_types_provided(Context) -> {Types, Context}
    when Context :: z:context(), Types :: list().
content_types_provided(Context) ->
    {[{<<"text">>, <<"plain">>, []}], Context}.

-spec process(Method, Accepted, Provided, Context) -> {Body, Context}
    when Method :: binary(), Accepted :: term(), Provided :: term(),
         Context :: z:context(), Body :: binary().
process(_Method, _Accepted, _Provided, Context) ->
    {<<"Welcome to the garden">>, Context}.

Add a rule to the application's priv/dispatch/garden list:

{garden_hello, ["garden-hello"], controller_garden_hello, []}

Compile, refresh discovery, and request /garden-hello on the site's hostname. Expect a plain-text response containing the greeting. Check dispatch if it returns another page. The rule above is one tuple inside the dispatch list, not an entire dispatch file.

This example deliberately returns public constant text. Private data needs explicit authorization callbacks and model checks; a write endpoint also needs method handling, input validation, and protection against unauthorized requests. Consult controller#controller_template for a built-in alternative and controller#controller_api for model-based HTTP access.

Also in: Developer guide

Referred by

Documentation

Glossary

Action An action is functionality that can be attached to a HTML element or event. Actions are wired to an element or event. Think of showing dialogs, posting…

Developer guide

Create a reusable module

Create apps_user/zotonic_mod_garden with the following files. This example adds a discoverable module without starting an extra process.

Developer guide

Create a page layout

Use an existing site base template as your starting point. Put shared document structure in the base and page-specific markup in blocks.

Category

Controllers

HTTP request handlers that connect dispatch rules to rendered or generated responses.

Developer guide

Follow a request to its template

Start with the URL that gives an unexpected result. Check its hostname: Zotonic uses it to select a site before matching the site's dispatch rules.

Cookbook

Add an HTTP controller

Use controller_template when a dispatch rule only needs to render a template. Write a custom controller when the endpoint needs additional request processing…