Template objects¶
piecutter‘s templates are Python representations of content to be rendered against data.
Note
You may not care about template objects, except you enter piecutter internals in order to write custom stuff such as loaders, cutters or writers. In other cases, using locations with loaders should be enough.
Single units VS collections¶
piecutter handles two types of templates:
- files: they are rendered as single units;
- directories: they are rendered as collections of files.
Loaders make the difference between single units and collections:
>>> import piecutter
>>> loader = piecutter.LocalLoader(root=u'demo/simple')
>>> loader.is_file(u'hello.txt')
True
>>> with loader(u'hello.txt') as template:
... template.is_file
True
>>> loader.is_dir(u'.')
True
>>> with loader(u'.') as template:
... template.is_dir
True
Typically, single units will be rendered as file-like object, and collections will be rendered as generator of file-like objects.
Create template from text¶
You can instantiate templates from text:
>>> import piecutter
>>> template = piecutter.TextTemplate("I'm a template")
>>> template # Doctest: +ELLIPSIS
<piecutter.templates.TextTemplate object at 0x...>
>>> print(template)
I'm a template
Create template from file¶
You can create templates from file-like objects:
>>> with open('demo/simple/hello.txt') as template_file:
... template = piecutter.FileTemplate(template_file)
... template # Doctest: +ELLIPSIS
... print(template)
<piecutter.templates.FileTemplate object at 0x...>
Hello {who}!
Create template from custom locations¶
You can use loaders to instantiate templates from custom locations:
>>> import pathlib
>>> loader = piecutter.LocalLoader(root=pathlib.Path('demo/simple'))
>>> with loader.open('hello.txt') as template:
... print(template)
Hello {who}!
You should be able to load files from almost everywhere, provided you have the right loaders. See Loaders for details.