Search code examples
pythonpyramidmako

How do I register a global mako function in pyramid from outside the template?


I'm building a pyramid application using mako templates.

How can I make a function be accessible in all my mako templates without having to <%namespace /> a file in each and every template?

Not that having to add the namespace tag is bad per se, but in this case I'm trying to add a filter function (for markdown processing). That does not belong in a template file, but is more of a library thing and belongs in a .py file.

I want to write this in my mako template:

<div class="main-content">
    {page_content | markdown }
</div>

To state that page_content contains markdown code and should be processed as such.


Solution

  • As requested by @kratenko you can use a BeforeRender subscriber as detailed here

    You can add the following subscriber in your view

    @subscriber(BeforeRender)
    def add_base_template(event):
      request = event.get('request')
      if request.user:
        base = 'myapp:templates/logged_in_layout.mako'
        event.update({'base': base})
      else:
        base = 'myapp:templates/layout.mako'
        event.update({'base': base})
    

    And in your mako template call it like so:

    <%inherit file="${context['base']}" />