pythontemplatesinheritancecheetah

How do I use inheritance in Cheetah templates?


For Cheetah3, there is a very rough documentation of the inheritance feature: http://cheetahtemplate.org/users_guide/inheritanceEtc.html#extends

But I don't get how to make it actually work.

Let's assume I have two template files:

A.tmpl

#def message
Hello Cheetah
#end def
This is an example: $message

B.tmpl

#extends A
#def message
Hello Cheetah with Inheritance
#end def

and a simple driver program such as:

from Cheetah.Template import Template

t = Template(file='B.tmpl')
print t

Obviously, that doesn't work, because there is no class A when executing this code.

But how does it go? Or is inheritance only possible with precompiled Cheetah templates?


Solution

  • There are two ways to import one template from the other.

    1. Compile all templates to *.py files using cheetah compile command line program. Then import works at the Python level.

    To semi-automatically compile all templates after you edit them I recommend the following Makefile (GNU flavour):

    .SUFFIXES: # Clear the suffix list
    .SUFFIXES: .py .tmpl
    
    %.py: %.tmpl
            cheetah compile --nobackup $<
            python -m compile $@
    
    templates = $(shell echo *.tmpl)
    modules = $(patsubst %.tmpl,%.py,$(templates))
    
    .PHONY: all
    all: $(modules)
    

    (Don't forget — makefiles require indent with tabs, not spaces.)

    1. Subvert Python import to make Cheetah import directly from *.tmpl files.

    Code:

    from Cheetah import ImportHooks
    ImportHooks.install()
    
    import sys
    sys.path.insert(0, 'path/to/template_dir')  # or sys.path.append
    

    PS. ImportHooks automatically try to import from *.pyc, *.py and *.tmpl — whatever is found first. A few days ago I extended ImportHooks to automatically compile *.tmpl to *.py and *.pyc. I'm going to write more docs and push in a few days. Expect the final release Cheetah 3.2 in a few months.