Question

Here's some code I use in Pyramid to load macros into my Chameleon templates:

@subscriber(BeforeRender)
def add_base_templates(event):
    """Define the base templates."""
    main_template = get_renderer('../templates/restaurant.pt').implementation()
    event.update({ 'main_template': main_template })

How would I achieve the same without Pyramid? For example, in this code:

from chameleon import PageTemplateFile

path = os.path.dirname(__file__)
lizard = PageTemplateFile(os.path.join(path, '..', 'emails', template+'.pt'))
html = lizard(**data)
Was it helpful?

Solution

Let's take a look at what your code does; all you have to do to use macros outside of pyramid is to replicate this.

  1. When you call .implementation() in pyramid, you are essentially retrieving a PageTemplateFile instance with the correct template path loaded.

  2. The BeforeRender event let's you modify the dict response from a view, and in your add_base_templates event handler you add a new entry named main_template.

Combine these two to get the same effect in your own code, passing in a main_template macro template when calling your lizard template:

from chameleon import PageTemplateFile

path = os.path.dirname(__file__)
main_template = PageTemplateFile(os.path.join(path, '..', 'templates', 'restaurant.pt'))
lizard = PageTemplateFile(os.path.join(path, '..', 'emails', template+'.pt'))
html = lizard(main_template=main_template, **data)

That's all there is to it, really.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top