pydocmaker.templating
Attributes
Classes
Manage templates, parameters, and attachments from specified directories. |
|
A class used to represent a document template. |
Functions
Detect the template engine type from a template string or file path. |
|
|
|
|
|
|
|
|
|
|
Register a new template directory if its not already registered. |
|
Removes an existing template directory if it exists. |
|
Returns a list of registered template directories. |
|
tests if a template with a given id and optional in a given format exists |
|
Retrieve the template IDs from the registered template directories. |
|
Retrieve the parameters for one or more templates. |
|
Resolve a template ID to its full file name. |
Module Contents
- pydocmaker.templating.TEMPLATE_EXTS
- pydocmaker.templating.default_template_dir
- pydocmaker.templating.registered_template_dirs
- pydocmaker.templating.determine_engine_from_template(template: jinja2.Template | str | pathlib.Path, tformat=None) str
Detect the template engine type from a template string or file path.
Accepts a Jinja2 Template object (extracts
filename), a file path string, or a raw template source string. Returns one of'html','typ', or'tex', orNoneif the engine cannot be determined.For file paths the engine is inferred from the file extension. For raw source strings the function looks for engine-specific markers such as
<html>,#set ``, or ``\documentclass.- Parameters:
template – A Jinja2 Template object, a file path string, or a raw template source string.
- Returns:
One of
'html','typ','tex', orNone.- Return type:
str or None
- pydocmaker.templating.get_template_source(template_obj: jinja2.Template)
- pydocmaker.templating.handle_template(template, default_template, tformat=None) Tuple[jinja2.Template, dict, str]
- pydocmaker.templating._remove_template_ext(filename)
- pydocmaker.templating._remove_template_ext_match(filename)
- pydocmaker.templating.register_new_template_dir(new_template_dir: str, check_exists=True) bool
Register a new template directory if its not already registered. NOTE: If its already registered this function does nothing without much overhead.
- Parameters:
new_template_dir (str) – The path to the new template directory.
check_exists (bool, optional) – Whether to check if the directory exists. Defaults to True.
- Raises:
FileNotFoundError – If the directory does not exist and check_exists is True.
- Returns:
True if the directory was successfully registered, False otherwise.
- Return type:
bool
- pydocmaker.templating.remove_from_template_dir(to_remove: str) bool
Removes an existing template directory if it exists.
- Parameters:
to_remove (str) – The path to remove from the template dirs.
- Returns:
Always True
- Return type:
bool
- pydocmaker.templating.get_registered_template_dirs(include_default=True)
Returns a list of registered template directories.
- Parameters:
include_default (bool, optional) – Whether to include the default template directory. Defaults to True.
- Returns:
- A list of registered template directories. If include_default is True, the default
template directory is the first element in the list.
- Return type:
list
- pydocmaker.templating.test_template_exists(template_id, tformat='', template_dir=None)
tests if a template with a given id and optional in a given format exists
- Parameters:
template_id (str) – the template id to search for e.G. ‘base’
tformat (str, optional) – optinal the template format to look for (e.g. ‘html’, ‘typ’, ‘tex’) if nothing is given the first found template with that name independent of the format is returned. Defaults to ‘’.
template_dir (str, optional) – if this is given only the given template directory is mounted to load jinja templates. Defaults to ‘’.
- Returns:
True if found False otherwise
- Return type:
bool
- pydocmaker.templating.get_available_template_ids(template_dir=None, tformat=None) list
Retrieve the template IDs from the registered template directories.
- Parameters:
template_dir (str, optional) – A specific template directory to search. If None, all registered template directories are searched.
tformat (str, optional) – Template format filter (e.g. ‘html’, ‘typ’, ‘tex’). If None, no format filtering is applied.
- Returns:
A list of template IDs (names without file extensions).
- Return type:
list
- pydocmaker.templating.get_template_params(template_id=None, template_dir=None, allow_fallback_jinja=True, tformat=None) dict
Retrieve the parameters for one or more templates.
When a .params.json file is found for a template, its contents are used as-is. When no .params.json file exists and
allow_fallback_jinjais True, parameters are inferred from the template source viafind_undeclared_variables, in which case all parameter values are set tojinja2.Undefinedwhich will be ignored on render.- Parameters:
template_id (str, optional) – A specific template ID to get parameters for. If None, parameters for all templates are returned.
template_dir (str, optional) – A specific template directory to search. If None, all registered template directories are searched.
allow_fallback_jinja (bool, optional) – If True and no .params.json file is found, infer parameters from undeclared variables in the template source. Defaults to True.
tformat (str, optional) – Template format filter (e.g. ‘html’, ‘typ’, ‘tex’). If None, no format filtering is applied.
- Returns:
- A dictionary of template parameters. If template_id is provided, the parameter dicts
is returned directly for template_id. If template_id is None, keys are template IDs mapping to their parameter dicts (including all templates).
- Return type:
dict
- pydocmaker.templating.resolve_template_id(template_id, template_dir=None, tformat=None, on_error='raise')
Resolve a template ID to its full file name.
- Parameters:
template_id (str) – The template ID to resolve (e.g. ‘base’, ‘base.html’, ‘base.html.j2’).
template_dir (str, optional) – A specific template directory to search. If None, all registered template directories are searched.
tformat (str, optional) – Template format filter (e.g. ‘html’, ‘typ’, ‘tex’). If None, no format filtering is applied.
on_error (str|Any, optional) – if this is anything but “raise” the given value will be returned on a KeyError.
- Returns:
The actual template file name resolved from the available templates.
- Return type:
str
- class pydocmaker.templating.TemplateDirSource(template_dirs: List[str] = None, tformat=None)
Manage templates, parameters, and attachments from specified directories.
…
- template_dirs
a list of directory paths where templates are located
- Type:
list
- env
an Environment object from the jinja2 library used to load templates
- Type:
Environment
- engine
The template engine type filter. When set, only templates matching the engine type are loaded (“html”, “typ” for templates starting with “typ”, or “tex” for templates ending with “tex”).
- Type:
str or None
- get_params(templates=None, allow_fallback_jinja=True)
Returns a dictionary of parameters for the specified templates.
- get_templates()
Returns a dictionary of Jinja2 Template objects keyed by template name.
- get_template_ids()
Returns a list of template IDs (names without file extensions).
- get_attachments(templates=None)
Returns a dictionary of attachments for the specified templates.
- get_all(load_params=True, load_attachments=True)
Returns a tuple of (templates dict, params dict, attachments dict).
- resolve_template_id(my_template_id)
Returns the full template file name corresponding to the given template ID.
- find_undeclared_variables(template)
Returns a set of variable names used in the template but not declared.
- VALID_ENGINES = ('html', 'typ', 'tex')
- template_dirs = None
- tformat = None
- env
- find_undeclared_variables(template: jinja2.Template | str)
Find undeclared variables in a Jinja2 template.
Accepts the
templateargument as any of the following:a
pathlib.Pathorstrtemplate ID (e.g."base.tex","base.html.j2") — the ID is resolved viaresolve_template_idso that{% extends %},{% include %}, etc. are followed through by jinja2’s loader.a
strcontaining raw Jinja2 template source codea Jinja2
Templateobject loaded from a file (has afilenameattribute pointing to an on-disk file)
Jinja2’s
env.parse()is used for all paths that go through the loader, which automatically traces{% extends %}/{% include %}and collects variables from all included/extended templates.Note: Jinja2 does not expose the original source of templates created via
Environment.from_string()(nameisNoneand there is nofilename). Passing such templates raisesValueError. Use a raw source string instead.- Parameters:
template – The template to analyze. See above for accepted types.
- Returns:
A set of undeclared variable names used in the template.
- Return type:
set
- get_params(templates: Iterable[str] = None, allow_fallback_jinja=True) dict
Returns a dictionary of (default) parameters for the specified templates.
When a .params.json file is found for a template, its contents are used as-is. When no .params.json file exists and
allow_fallback_jinjais True, parameters are inferred from the template source viafind_undeclared_variables, in which case all parameter values are set tojinja2.Undefinedwhich will be ignored on render.- Parameters:
templates (iterable str) – An iterable of template ids/names. If None, all templates are loaded.
allow_fallback_jinja (bool, optional) – If True and no .params.json file is found for a template, infer parameters from undeclared variables in the template source with
Nonevalues. Defaults to True.
- Returns:
- A dictionary keyed by template_id, where each value is a dict of
param_name to param_value. When parameters come from a .params.json file, values are as defined in that file. When inferred via the Jinja2 fallback, all values are
None.
- Return type:
dict
- get(template_id: str, default=None)
- _template_matches_engine(template_name)
Check if a template name matches the configured engine filter.
- get_templates() dict
Retrieves all the templates from the directory.
- Returns:
- A dictionary of templates where the keys are the template names
and the values are the corresponding Jinja2 Template objects.
- Return type:
dict
- get_template_ids()
This function retrieves the template IDs from the list of templates.
- Returns:
A list of template IDs, which are the names of the templates without the file extension.
- Return type:
list
- get_attachments(templates=None)
Get attachments from the template directory.
- Parameters:
templates (list or dict, optional) – A list or dictionary of templates. If None, all templates will be used. Defaults to None.
- Returns:
- A dictionary of attachments, where the keys are the template names
and the values are dictionaries of attachments for that template.
- Return type:
dict
- get_all_filenames()
Get all filenames in all template directories.
- get_all(load_params=True, load_attachments=True)
Get all templates, parameters, and attachments.
- Parameters:
load_params (bool, optional) – Whether to load parameters. Defaults to True.
load_attachments (bool, optional) – Whether to load attachments. Defaults to True.
- Returns:
A tuple containing templates, parameters, and attachments.
- Return type:
tuple
- resolve_template_id(my_template_id)
Resolve the template ID to the actual template file name.
- Parameters:
my_template_id (str) – The template ID to resolve.
- Returns:
The actual template file name.
- Return type:
str
- Raises:
KeyError – If the template ID is not found in the available templates.
- __contains__(template_id)
Check if a template_id is in any of the template directories.
- class pydocmaker.templating.DocTemplate(template, params=None, attachments=None, env=None, template_id=None)
A class used to represent a document template.
This class provides methods to load a template from a template directory, render the template with given parameters, and manage attachments.
- template
A string representation of the template.
- Type:
str
- params
A dictionary of parameters to be used in the template.
- Type:
dict
- attachments
A dictionary of attachments to be used in the template.
- Type:
dict
- env
An instance of the jinja2 Environment class.
- Type:
Environment
- static from_tid(template_id: str, tformat='', template_dir=None)
Load a template by supplying a template_id and possibly a template format
- Parameters:
template_id (str) – The ID of the template to load e.G. “base”
tformat (str, optional) – optinal the template format to get e.G. “.tex” or “.html”. Defaults to ‘’ which means first of any format being found.
template_dir (str, optional) – The directory containing the templates. If not provided, the default template directory is used.
- Returns:
An instance of the DocTemplate class.
- Return type:
- static test_tid_exists(template_id: str, tformat='', template_dir=None)
Test if a template with the given ID and optional format exists.
- Parameters:
template_id (str) – The template ID to search for (e.g. ‘base’).
tformat (str, optional) – The template format to look for (‘tex’, ‘html’, etc.). If empty, checks for any format. Defaults to ‘’.
template_dir (str, optional) – If given, only the specified template directory is searched. Defaults to None.
- Returns:
True if a template with the given ID (and optional format) exists.
- Return type:
bool
- static get_available_tids(template_dir=None)
Get the list of available template IDs.
- Parameters:
template_dir (str, optional) – A specific template directory to search. If None, all registered template directories are searched.
- Returns:
A list of template IDs (names without file extensions).
- Return type:
list
- template
- params = None
- attachments = None
- env
- template_id = None
- property tformat
- __str__()
- __repr__()
- render(**kwargs)
Render the Jinja2 template with given parameters.
- Parameters:
**kwargs – Additional parameters to be used in the template.
- Returns:
The rendered template as a string.
- Return type:
str
- pydocmaker.templating.res = False