Finds all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `None`, instead of in a zipfile, the templates will be stored in a directory. By default a deflate zip algorithm is used. To switch to the stored algorithm, `zip` can
(
self,
target: t.Union[str, "os.PathLike[str]"],
extensions: t.Optional[t.Collection[str]] = None,
filter_func: t.Optional[t.Callable[[str], bool]] = None,
zip: t.Optional[str] = "deflated",
log_function: t.Optional[t.Callable[[str], None]] = None,
ignore_errors: bool = True,
)
| 816 | return TemplateExpression(template, undefined_to_none) |
| 817 | |
| 818 | def compile_templates( |
| 819 | self, |
| 820 | target: t.Union[str, "os.PathLike[str]"], |
| 821 | extensions: t.Optional[t.Collection[str]] = None, |
| 822 | filter_func: t.Optional[t.Callable[[str], bool]] = None, |
| 823 | zip: t.Optional[str] = "deflated", |
| 824 | log_function: t.Optional[t.Callable[[str], None]] = None, |
| 825 | ignore_errors: bool = True, |
| 826 | ) -> None: |
| 827 | """Finds all the templates the loader can find, compiles them |
| 828 | and stores them in `target`. If `zip` is `None`, instead of in a |
| 829 | zipfile, the templates will be stored in a directory. |
| 830 | By default a deflate zip algorithm is used. To switch to |
| 831 | the stored algorithm, `zip` can be set to ``'stored'``. |
| 832 | |
| 833 | `extensions` and `filter_func` are passed to :meth:`list_templates`. |
| 834 | Each template returned will be compiled to the target folder or |
| 835 | zipfile. |
| 836 | |
| 837 | By default template compilation errors are ignored. In case a |
| 838 | log function is provided, errors are logged. If you want template |
| 839 | syntax errors to abort the compilation you can set `ignore_errors` |
| 840 | to `False` and you will get an exception on syntax errors. |
| 841 | |
| 842 | .. versionadded:: 2.4 |
| 843 | """ |
| 844 | from .loaders import ModuleLoader |
| 845 | |
| 846 | if log_function is None: |
| 847 | |
| 848 | def log_function(x: str) -> None: |
| 849 | pass |
| 850 | |
| 851 | assert log_function is not None |
| 852 | assert self.loader is not None, "No loader configured." |
| 853 | |
| 854 | def write_file(filename: str, data: str) -> None: |
| 855 | if zip: |
| 856 | info = ZipInfo(filename) |
| 857 | info.external_attr = 0o755 << 16 |
| 858 | zip_file.writestr(info, data) |
| 859 | else: |
| 860 | with open(os.path.join(target, filename), "wb") as f: |
| 861 | f.write(data.encode("utf8")) |
| 862 | |
| 863 | if zip is not None: |
| 864 | from zipfile import ZIP_DEFLATED |
| 865 | from zipfile import ZIP_STORED |
| 866 | from zipfile import ZipFile |
| 867 | from zipfile import ZipInfo |
| 868 | |
| 869 | zip_file = ZipFile( |
| 870 | target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip] |
| 871 | ) |
| 872 | log_function(f"Compiling into Zip archive {target!r}") |
| 873 | else: |
| 874 | if not os.path.isdir(target): |
| 875 | os.makedirs(target) |