################ 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 :doc:`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. :doc:`Loaders ` make the difference between single units and collections: .. doctest:: >>> 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: .. doctest:: >>> import piecutter >>> template = piecutter.TextTemplate("I'm a template") >>> template # Doctest: +ELLIPSIS >>> print(template) I'm a template ************************* Create template from file ************************* You can create templates from file-like objects: .. doctest:: >>> with open('demo/simple/hello.txt') as template_file: ... template = piecutter.FileTemplate(template_file) ... template # Doctest: +ELLIPSIS ... print(template) Hello {who}! ************************************* Create template from custom locations ************************************* You can use :doc:`loaders ` to instantiate templates from custom locations: .. doctest:: >>> 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 :doc:`/loaders` for details. ****************************** Create template from directory ****************************** You can create templates from directories using :doc:`loaders `: .. doctest:: >>> loader = piecutter.LocalLoader(root=pathlib.Path('demo/simple')) >>> print(loader.tree('.')) [u'hello.txt', u'{who}.txt']