Chameleon macros without Pyramid
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)
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.
When you call
.implementation()
in pyramid, you are essentially retrieving aPageTemplateFile
instance with the correct template path loaded.The
BeforeRender
event let's you modify the dict response from a view, and in youradd_base_templates
event handler you add a new entry namedmain_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.