Dispatch fallback

27 views
Skip to first unread message

Marc Worrell

unread,
May 2, 2012, 4:11:38 PM5/2/12
to zotonic-d...@googlegroups.com, zotoni...@googlegroups.com
Hi,

TL;DR;

When (in 0.9dev) you add a template like:

/templates/static/hello.tpl

Then the request:


will serve that template.
Without adding any dispatch rules.


Long version:

I just added a new notification to the 0.9dev.
It is called #dispatch{} and is used by the site dispatcher to find a matching dispatch rule when no rule matched.

The #dispatch{} observer can return:

- {ok, integer()} where the integer is a rsc id
- {ok, #dispatch_match{}}  with a webmachine resource and options filled in
- {ok, #dispatch_redirect{}} to redirect to a location (must be a fully qualified url!)
- undefined

With an 'undefined' other modules will be checked and finally a 404 might be served.

In mod_base I added a handler for the #dispatch{} notification:

%% @doc Check if there is a resource or template matching the path.
observe_dispatch(#dispatch{path=Path}, Context) ->
    case m_rsc:page_path_to_id(Path, Context) of
        {ok, Id} ->
            {ok, Id};
        {error, _} ->
            Template = "static/"++Path++".tpl",
            case z_module_indexer:find(template, Template, Context) of
                {ok, _} ->
                    {ok, #dispatch_match{
                        mod=resource_template,
                        mod_opts=[{template, Template}, {ssl, any}],
                        bindings=[{path, Path}, {is_static, true}]
                    }};
                {error, _} ->
                    undefined
            end
    end.

This does two things:

1. Check if there is resource with a set page path, if so return it's id
2. Check if there is a template in a 'static/' directory with the name of the request path.
    If so then this template is served using the resource_template module

- Marc

Dmitrii Dimandt

unread,
May 3, 2012, 2:17:24 AM5/3/12
to zotonic-d...@googlegroups.com
One word: AWESOME!

M-MZ

unread,
May 3, 2012, 2:34:47 AM5/3/12
to zotonic-d...@googlegroups.com, zotoni...@googlegroups.com
Very cool. love it. That also allows other modules to observe dispatch requests... Endless possibilities.

Maas
Reply all
Reply to author
Forward
0 new messages