Skip to main content
Version: 0.2

Create custom context producers

Marten has built-in support for common context producers, but the framework also allows you to write your own context producers that you can leverage as part of your project's templates. This allows you to easily reuse common context values over multiple templates.

Defining a context producer

Defining a context producer involves creating a subclass of the Marten::Template::ContextProducer abstract class. This abstract class requires that subclasses implement a single #produce method: this method takes an optional request object as argument and must return either:

  • a hash or a named tuple containing the values to contribute to the template context
  • or nil if no values can be generated for the passed request

For example, the following context producer would expose the value of the debug setting to all the template contexts being created:

class Debug < Marten::Template::ContextProducer
def produce(request : Marten::HTTP::Request? = nil)
{"debug" => Marten.settings.debug}

Activating context producers

As mentioned in Using context producers, context producers classes must be added to the templates.context_producers setting in order to be used by the Marten templates engine when initializing new context objects.