简体   繁体   中英

Chameleon macros without Pyramid

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM