1. Justin Sheehy
  2. webmachine
  3. Issues
Issue #4 resolved

Adding support to a template library?

matteoredaelli
created an issue

Ciao

What about adding support to a template system (for instance http://code.google.com/p/erlydtl/) like http://beepbeep.dmitriid.com/en-US/ microfamework?

Thanks http://www.redaelli.org/matteo/

Comments (1)

  1. Bryan Fink

    Done! Just return the result of the rendering from your content-producing function. For example:

    to_html(ReqData, Context) ->
       {ok, Data} = my_erlydtl_template:render(Context),
       {Data, ReqData, Context}.
    

    That pattern should work for any template system that produces an iolist output in some manner. (Indeed, developers have already used ErlyDTL, ErlTL, many home-grown and other template systems just like this.)

    If you're looking for a more natural way to deal with lots of templates, without writing lots of webmachine resources, my suggestion would be to write a generic resource that can be initialized with the template to render, then use the dispatcher to choose which template to render.

    For example:

    -module(wm_template).
    
    init(Template) -> {ok, #context{template=Template}.
    
    to_html(ReqData, Context#context{template=T}) ->
       {ok, Data} = T:render(Context),
       {Data, ReqData, Context}.
    

    Could be parameterized by the dispatch:

    {["foo"], wm_template, foo_template}.
    {["bar"], wm_template, bar_template}.
    

    A more complex resource that chose from a list of possible templates based on other data in the request would also be possible, of course.

  2. Log in to comment