martenframework / marten

The pragmatic web framework.
https://martenframework.com
MIT License
405 stars 23 forks source link

Add global context object to handlers #137

Closed ellmetha closed 8 months ago

ellmetha commented 8 months ago

Description

Presently, handlers that render templates must either override the #context method or specify context values to the #render method in order to customize what variables are available to the template runtime. This does not make it easy to contribute new context values through the use of concern modules, and having to override methods and call #super in these methods isn't ideal nor evident for newcomers to the framework.

To improve the situation, let's replace existing #context methods with the use of a global context object. This global context object will be available through the use of a unique #context method and will be mutable for the lifespan of the considered handler. Coupled with the use of the #before_render callback (#113), it will become simpler to define custom context values.

For example:

class ArticleListHandler < Marten::Handler
  def get
    context[:articles] = Article.all

    render "articles/list.html"
  end
end