dotprompt-handlebars 0.0.1.dev1__cp312-cp312-manylinux_2_34_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of dotprompt-handlebars might be problematic. Click here for more details.

@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: dotprompt_handlebars
3
+ Version: 0.0.1.dev1
4
+ Classifier: Development Status :: 3 - Alpha
5
+ Classifier: Programming Language :: Python :: 3
6
+ Classifier: Programming Language :: Python :: 3.10
7
+ Classifier: Programming Language :: Python :: 3.11
8
+ Classifier: Programming Language :: Python :: 3.12
9
+ Classifier: Programming Language :: Python :: 3.13
10
+ Classifier: Programming Language :: Rust
11
+ Classifier: Topic :: Text Processing :: Markup
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Requires-Dist: strenum>=0.4.15 ; python_full_version < '3.11'
14
+ Requires-Dist: structlog>=25.2.0
15
+ License-File: LICENSE
16
+ Summary: Handlebars library for Python based on handlebars-rust.
17
+ Home-Page: https://github.com/google/dotprompt
18
+ Author: Yesudeep Mangalapilly <yesudeep@google.com>
19
+ Author-email: Yesudeep Mangalapilly <yesudeep@google.com>
20
+ License: Apache-2.0
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
23
+ Project-URL: Source Code, https://github.com/google/dotprompt
24
+
25
+ # dotprompt-handlebars
26
+
27
+ **DISCLAIMER**: Project only intended to be used for dotprompt package. Support for other use cases is not guaranteed.
@@ -0,0 +1,8 @@
1
+ dotprompt_handlebars-0.0.1.dev1.dist-info/METADATA,sha256=9_xBpQnwIVm71CTHLHmtbtuCE--s2vPbFOXSwzTs6_E,1174
2
+ dotprompt_handlebars-0.0.1.dev1.dist-info/WHEEL,sha256=7FgAcpQES0h1xhfN9Ugve9FTUilU6sRAr1WJ5ph2cuw,108
3
+ dotprompt_handlebars-0.0.1.dev1.dist-info/licenses/LICENSE,sha256=bsvE5_qSn_2LH2G-haMvT_AoIeINhX6fvzZTlyq2xJY,11340
4
+ handlebarrz/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ handlebarrz/__init__.py,sha256=pxIV7rtRAfnOlv6q3oPiNT1Srs2KR3CYrWtVAksDCKw,18124
6
+ handlebarrz/_native.pyi,sha256=GhUc2bN9WHgl4OKBRLMjvPi4mg7FzVrXBsMpgajsiVo,2063
7
+ handlebarrz/_native.cpython-312-x86_64-linux-gnu.so,sha256=5qExRL6rSQ-Ezl-e8f_sgPMshxNM2x2DgRHw8tZsWwA,1500384
8
+ dotprompt_handlebars-0.0.1.dev1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: maturin (1.8.3)
3
+ Root-Is-Purelib: false
4
+ Tag: cp312-cp312-manylinux_2_34_x86_64
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Google LLC
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,544 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Python wrapper for the Handlebars templating language using handlebars-rust.
18
+
19
+ It supports most Handlebars functionality including template registration,
20
+ rendering, partials, block helpers, custom helpers, subexpressions, inline
21
+ partials, and various configuration options.
22
+
23
+ ## Features:
24
+
25
+ - Block helpers with inverse sections (`else` blocks)
26
+ - Built-in helpers (`each`, `if`, `unless`, `with`, `lookup`, `log`)
27
+ - Context navigation (`this`, `../parent`, `@root`)
28
+ - Custom helper functions
29
+ - Development mode for automatic template reloading
30
+ - HTML escaping options and customization
31
+ - Partial templates and blocks
32
+ - Strict mode for missing fields
33
+ - Subexpressions and parameter literals
34
+ - Template registration (strings, files, directories)
35
+ - Whitespace control with `~` operator
36
+
37
+ ## Example
38
+
39
+ ```python
40
+ # Using the Template class.
41
+ from handlebarrz import Template
42
+
43
+ template = Template()
44
+ template.register_template('hello', 'Hello {{name}}!')
45
+ result = template.render('hello', {'name': 'World'})
46
+ # result = "Hello World!"
47
+
48
+ # Using the Handlebars alias.
49
+ from handlebarrz import Handlebars
50
+
51
+ handlebars = Handlebars()
52
+ handlebars.register_template('greeting', 'Hello {{name}}!')
53
+ result = handlebars.render('greeting', {'name': 'World'}) # "Hello World!"
54
+
55
+
56
+ # Using custom helpers.
57
+ def format_name(params, hash, ctx):
58
+ name = params[0]
59
+ return name.upper() if hash.get('uppercase') else name
60
+
61
+
62
+ handlebars.register_helper('format', format_name)
63
+ handlebars.register_template(
64
+ 'formatted', 'Hello {{format name uppercase=true}}!'
65
+ )
66
+ result = handlebars.render('formatted', {'name': 'World'}) # "Hello WORLD!"
67
+ ```
68
+ """
69
+
70
+ import json
71
+ import sys # noqa
72
+ from collections.abc import Callable
73
+ from pathlib import Path
74
+ from typing import Any
75
+
76
+ import structlog
77
+
78
+ if sys.version_info < (3, 11): # noqa
79
+ from strenum import StrEnum # noqa
80
+ else: # noqa
81
+ from enum import StrEnum # noqa
82
+
83
+ from ._native import (
84
+ HandlebarrzTemplate,
85
+ html_escape,
86
+ no_escape,
87
+ )
88
+
89
+ logger = structlog.get_logger(__name__)
90
+
91
+
92
+ HelperFn = Callable[[list[Any], dict[str, Any], dict[str, Any]], str]
93
+ NativeHelperFn = Callable[[str, str, str], str]
94
+
95
+
96
+ class EscapeFunction(StrEnum):
97
+ """Enumeration of built-in escape functions for Handlebars templates.
98
+
99
+ These constants define how content is escaped when rendered in templates.
100
+ By default, Handlebars escapes HTML entities in variables to prevent XSS
101
+ attacks, but this behavior can be customized:
102
+
103
+ | Character | HTML Entity |
104
+ |-----------|-------------|
105
+ | `&` | `&amp;` |
106
+ | `<` | `&lt;` |
107
+ | `>` | `&gt;` |
108
+ | `"` | `&quot;` |
109
+ | `'` | `&#x27;` |
110
+
111
+ Attributes:
112
+ HTML_ESCAPE: Escapes HTML entities (default)
113
+ NO_ESCAPE: Passes content through without any escaping
114
+ """
115
+
116
+ HTML_ESCAPE = 'html_escape'
117
+ NO_ESCAPE = 'no_escape'
118
+
119
+
120
+ class Template:
121
+ """A Handlebars template engine that can register and render templates.
122
+
123
+ This class wraps the Rust implementation of Handlebars and provides a
124
+ Pythonic interface for template registration, rendering, and configuration.
125
+ The following language features are supported:
126
+
127
+ * Block Expressions: `{{#block}}...{{/block}}`
128
+ * Block Helpers: `{{#helper}}...{{else}}...{{/helper}}`
129
+ * Comments: `{{! comment }}`
130
+ * Expressions: `{{var}}`, `{{{var}}}`, `{{&var}}`
131
+ * Helpers: `{{helper param1 param2 key=value}}`
132
+ * Literals: `{{helper "string" 123 true null undefined}}`
133
+ * Partials: `{{> partial}}`
134
+ * Path Navigation: `{{../parent}}`, `{{this}}`, `{{@root}}`
135
+ * Subexpressions: `{{helper (subhelper param) param2}}`
136
+ * Whitespace Control: `{{~helper}}` or `{{helper~}}`
137
+
138
+ Attributes:
139
+ strict_mode: Whether to raise errors for missing fields in templates.
140
+ dev_mode: Whether to enable development mode features for
141
+ auto-reloading.
142
+ """
143
+
144
+ def __init__(
145
+ self,
146
+ escape_fn: EscapeFunction = EscapeFunction.HTML_ESCAPE,
147
+ strict_mode: bool = False,
148
+ dev_mode: bool = False,
149
+ ) -> None:
150
+ """Create a new Handlebars template engine.
151
+
152
+ Args:
153
+ escape_fn: The escape function to use for HTML escaping.
154
+ strict_mode: Whether to raise errors for missing fields in templates.
155
+ dev_mode: Whether to enable development mode features for
156
+ auto-reloading.
157
+ """
158
+ self._template: HandlebarrzTemplate = HandlebarrzTemplate()
159
+ self._template.set_escape_fn(escape_fn)
160
+ self._template.set_strict_mode(strict_mode)
161
+ self._template.set_dev_mode(dev_mode)
162
+
163
+ @property
164
+ def strict_mode(self) -> bool:
165
+ """Whether the strict mode setting is enabled.
166
+
167
+ Returns:
168
+ Whether the strict mode setting is enabled.
169
+ """
170
+ return self._template.get_strict_mode()
171
+
172
+ @strict_mode.setter
173
+ def strict_mode(self, enabled: bool) -> None:
174
+ """Set strict mode.
175
+
176
+ This turns typos, missing field access, and undefined variables into
177
+ errors.
178
+
179
+ Args:
180
+ enabled: Whether strict mode should be enable.
181
+ """
182
+ self._template.set_strict_mode(enabled)
183
+ logger.debug({'event': 'strict_mode_changed', 'enabled': enabled})
184
+
185
+ @property
186
+ def dev_mode(self) -> bool:
187
+ """Whether dev mode has been enabled.
188
+
189
+ Returns:
190
+ Whether dev mode has been enabled.
191
+ """
192
+ return self._template.get_dev_mode()
193
+
194
+ @dev_mode.setter
195
+ def dev_mode(self, enabled: bool) -> None:
196
+ """Set development mode for this template engine.
197
+
198
+ In dev mode, templates are automatically reloaded from file when
199
+ modified. This is useful during development to see changes without
200
+ restarting the application.
201
+
202
+ Args:
203
+ enabled: Whether to enable development mode
204
+ """
205
+ self._template.set_dev_mode(enabled)
206
+ logger.debug({'event': 'dev_mode_changed', 'enabled': enabled})
207
+
208
+ def set_escape_function(self, escape_fn: EscapeFunction) -> None:
209
+ """Set the escape function used for HTML escaping.
210
+
211
+ Controls how variable values are escaped when rendered with the
212
+ `{{var}}` syntax (triple stache `{{{var}}}` and ampersand `{{&var}}`
213
+ will still be rendered unescaped).
214
+
215
+ Args:
216
+ escape_fn: The escape function to use, one of the values from
217
+ EscapeFunction
218
+
219
+ Raises:
220
+ ValueError: If the escape function is not recognized
221
+ """
222
+ try:
223
+ self._template.set_escape_fn(escape_fn)
224
+ logger.debug({
225
+ 'event': 'escape_function_changed',
226
+ 'function': escape_fn,
227
+ })
228
+ except ValueError as e:
229
+ logger.error({'event': 'escape_function_error', 'error': str(e)})
230
+ raise
231
+
232
+ def register_template(self, name: str, template_string: str) -> None:
233
+ """Register a template with the given name.
234
+
235
+ Templates are parsed and validated at registration time, which allows
236
+ for early detection of syntax errors. Registered templates can be
237
+ rendered multiple times with different contexts without reparsing.
238
+
239
+ Args:
240
+ name: The name to register the template under
241
+ template_string: The template string to register
242
+
243
+ Raises:
244
+ ValueError: If there is a syntax error in the template
245
+ """
246
+ try:
247
+ self._template.register_template(name, template_string)
248
+ logger.debug({'event': 'template_registered', 'name': name})
249
+ except ValueError as e:
250
+ logger.error({
251
+ 'event': 'template_registration_error',
252
+ 'name': name,
253
+ 'error': str(e),
254
+ })
255
+ raise
256
+
257
+ def register_partial(self, name: str, template_string: str) -> None:
258
+ """Register a partial with the given name.
259
+
260
+ Partials are templates that can be included in other templates using the
261
+ `{{> partial_name}}` syntax. They can receive the current context or a
262
+ custom context.
263
+
264
+ Args:
265
+ name: The name to register the partial under
266
+ template_string: The partial template string
267
+
268
+ Raises:
269
+ ValueError: If there is a syntax error in the template
270
+ """
271
+ try:
272
+ self._template.register_partial(name, template_string)
273
+ logger.debug({'event': 'partial_registered', 'name': name})
274
+ except ValueError as e:
275
+ logger.error({
276
+ 'event': 'partial_registration_error',
277
+ 'name': name,
278
+ 'error': str(e),
279
+ })
280
+ raise
281
+
282
+ def register_template_file(self, name: str, file_path: str | Path) -> None:
283
+ """Register a template from a file.
284
+
285
+ Reads the template from the specified file and registers it under the
286
+ given name. In development mode, the template will be automatically
287
+ reloaded when the file changes.
288
+
289
+ Args:
290
+ name: The name to register the template under
291
+ file_path: Path to the template file
292
+
293
+ Raises:
294
+ FileNotFoundError: If the template file does not exist
295
+ ValueError: If there is a syntax error in the template
296
+ """
297
+ file_path_str = str(file_path)
298
+ try:
299
+ self._template.register_template_file(name, file_path_str)
300
+ logger.debug({
301
+ 'event': 'template_file_registered',
302
+ 'name': name,
303
+ 'path': file_path_str,
304
+ })
305
+ except (FileNotFoundError, ValueError) as e:
306
+ logger.error({
307
+ 'event': 'template_file_registration_error',
308
+ 'name': name,
309
+ 'path': file_path_str,
310
+ 'error': str(e),
311
+ })
312
+ raise
313
+
314
+ def register_templates_directory(self, dir_path: str | Path, extension: str = '.hbs') -> None:
315
+ """Register all templates in a directory.
316
+
317
+ Recursively finds all files with the specified extension in the
318
+ directory and registers them as templates. The template name will be the
319
+ file path relative to the directory, without the extension.
320
+
321
+ Args:
322
+ dir_path: Path to the directory containing templates
323
+ extension: File extension for templates, defaults to ".hbs"
324
+
325
+ Raises:
326
+ FileNotFoundError: If the directory does not exist
327
+ ValueError: If there is a syntax error in any template
328
+ """
329
+ dir_path_str = str(dir_path)
330
+ try:
331
+ self._template.register_templates_directory(dir_path_str, extension)
332
+ logger.debug({
333
+ 'event': 'templates_directory_registered',
334
+ 'path': dir_path_str,
335
+ 'extension': extension,
336
+ })
337
+ except (FileNotFoundError, ValueError) as e:
338
+ logger.error({
339
+ 'event': 'templates_directory_registration_error',
340
+ 'path': dir_path_str,
341
+ 'extension': extension,
342
+ 'error': str(e),
343
+ })
344
+ raise
345
+
346
+ def register_helper(
347
+ self,
348
+ name: str,
349
+ helper_fn: HelperFn,
350
+ ) -> None:
351
+ """Register a helper function.
352
+
353
+ Helpers extend the templating engine with custom functionality. They can
354
+ be called from templates using the `{{helper_name arg1 arg2 key=value}}`
355
+ syntax.
356
+
357
+ The helper function should take three parameters:
358
+ - params: List of positional parameters passed to the helper
359
+ - hash: Dictionary of named parameters (hash) passed to the helper
360
+ - context: Dictionary containing the current context
361
+
362
+ It should return a string that will be inserted into the template.
363
+
364
+ Examples:
365
+ ```python
366
+ # A helper that formats a date
367
+ def format_date(params, hash, ctx):
368
+ date_obj = params[0]
369
+ format_str = hash.get('format', '%Y-%m-%d')
370
+ return date_obj.strftime(format_str)
371
+
372
+
373
+ template.register_helper('formatDate', format_date)
374
+
375
+ # Usage in template:
376
+ # {{formatDate date format="%-d %B %Y"}}
377
+ ```
378
+
379
+ Args:
380
+ name: The name to register the helper under
381
+ helper_fn: The helper function
382
+ """
383
+ try:
384
+ # TODO: Fix this type error.
385
+ self._template.register_helper(name, create_helper(helper_fn)) # type: ignore[arg-type]
386
+ logger.debug({'event': 'helper_registered', 'name': name})
387
+ except Exception as e:
388
+ logger.error({
389
+ 'event': 'helper_registration_error',
390
+ 'name': name,
391
+ 'error': str(e),
392
+ })
393
+ raise
394
+
395
+ def has_template(self, name: str) -> bool:
396
+ """Determines whether the template with teh given name exists.
397
+
398
+ Args:
399
+ name: Name of the template.
400
+
401
+ Returns:
402
+ Whether the template exists.
403
+ """
404
+ return self._template.has_template(name)
405
+
406
+ def unregister_template(self, name: str) -> None:
407
+ """Unregister a template with the given name.
408
+
409
+ Removes the template from the registry if it exists.
410
+
411
+ Args:
412
+ name: The name of the template to unregister.
413
+ """
414
+ self._template.unregister_template(name)
415
+ logger.debug({'event': 'template_unregistered', 'name': name})
416
+
417
+ def render(self, name: str, data: dict[str, Any]) -> str:
418
+ """Render a template with the given data.
419
+
420
+ Renders a previously registered template using the provided data
421
+ context. The data is converted to JSON before being passed to the
422
+ template engine.
423
+
424
+ Args:
425
+ name: The name of the template to render
426
+ data: The data to render the template with
427
+
428
+ Returns:
429
+ str: The rendered template string
430
+
431
+ Raises:
432
+ ValueError: If the template does not exist or there is a rendering
433
+ error.
434
+ """
435
+ try:
436
+ result = self._template.render(name, json.dumps(data))
437
+ logger.debug({'event': 'template_rendered', 'name': name})
438
+ return result
439
+ except ValueError as e:
440
+ logger.error({
441
+ 'event': 'template_rendering_error',
442
+ 'name': name,
443
+ 'error': str(e),
444
+ })
445
+ raise
446
+
447
+ def render_template(self, template_string: str, data: dict[str, Any]) -> str:
448
+ """Render a template string directly without registering it.
449
+
450
+ Parses and renders the template string in one step. This is useful for
451
+ one-off template rendering, but for templates that will be rendered
452
+ multiple times, it's more efficient to register them first.
453
+
454
+ Args:
455
+ template_string: The template string to render
456
+ data: The data to render the template with
457
+
458
+ Returns:
459
+ Rendered template string.
460
+
461
+ Raises:
462
+ ValueError: If there is a syntax error in the template or a
463
+ rendering error.
464
+ """
465
+ try:
466
+ result = self._template.render_template(template_string, json.dumps(data))
467
+ logger.debug({'event': 'template_string_rendered'})
468
+ return result
469
+ except ValueError as e:
470
+ logger.error({
471
+ 'event': 'template_string_rendering_error',
472
+ 'error': str(e),
473
+ })
474
+ raise
475
+
476
+ def register_extra_helpers(self) -> None:
477
+ """Registers extra helper functions.
478
+
479
+ - `ifEquals`
480
+ - `unlessEquals`
481
+ - `json`
482
+
483
+ These helpers are not registered by default and must be registered
484
+ explicitly if needed.
485
+ """
486
+ try:
487
+ self._template.register_extra_helpers()
488
+ logger.debug({'event': 'extra_helpers_registered'})
489
+ except Exception as e:
490
+ logger.error({
491
+ 'event': 'extra_helpers_registration_error',
492
+ 'error': str(e),
493
+ })
494
+ raise
495
+
496
+
497
+ def create_helper(
498
+ fn: HelperFn,
499
+ ) -> NativeHelperFn:
500
+ """Create a helper function compatible with the Rust interface.
501
+
502
+ This function adapts a Python function with typed parameters to the format
503
+ expected by the Rust bindings. It handles the serialization and
504
+ deserialization of JSON data between Rust and Python.
505
+
506
+ Helper functions in Handlebars can be used for various purposes:
507
+
508
+ - Conditional rendering with custom logic.
509
+ - Formatting data (dates, numbers, strings).
510
+ - Generating HTML or other output formats.
511
+ - Implementing custom block helpers.
512
+ - Transforming data (sorting, filtering, mapping).
513
+
514
+ Args:
515
+ fn: A function taking of type HelperFn (params, hash, context).
516
+
517
+ Returns:
518
+ Function compatible with the Rust interface.
519
+ """
520
+
521
+ def wrapper(params_json: str, hash_json: str, ctx_json: str) -> str:
522
+ params = json.loads(params_json)
523
+ hash = json.loads(hash_json)
524
+ ctx = json.loads(ctx_json)
525
+
526
+ result = fn(params, hash, ctx)
527
+ return result
528
+
529
+ return wrapper
530
+
531
+
532
+ # Alias Template as Handlebars. This is done because the JS implementation
533
+ # calls its template class `Handlebars` so mostly for familiarity.
534
+ Handlebars = Template
535
+
536
+
537
+ __all__ = [
538
+ 'EscapeFunction',
539
+ 'Handlebars',
540
+ 'Template',
541
+ 'create_helper',
542
+ 'html_escape',
543
+ 'no_escape',
544
+ ]
@@ -0,0 +1,58 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Stub type annotations for native Handlebars."""
18
+
19
+ from collections.abc import Callable
20
+
21
+ def html_escape(text: str) -> str: ...
22
+ def no_escape(text: str) -> str: ...
23
+
24
+ class HandlebarrzTemplate:
25
+ """Stub type annotations for native Handlebars."""
26
+
27
+ def __init__(self) -> None: ...
28
+
29
+ # Strict mode.
30
+ def get_strict_mode(self) -> bool: ...
31
+ def set_strict_mode(self, enabled: bool) -> None: ...
32
+
33
+ # Dev mode.
34
+ def get_dev_mode(self) -> bool: ...
35
+ def set_dev_mode(self, enabled: bool) -> None: ...
36
+
37
+ # Escape function.
38
+ def set_escape_fn(self, escape_fn: str) -> None: ...
39
+
40
+ # Template registration.
41
+ def register_template(self, name: str, template_string: str) -> None: ...
42
+ def register_partial(self, name: str, template_string: str) -> None: ...
43
+ def register_template_file(self, name: str, file_path_str: str) -> None: ...
44
+ def register_templates_directory(self, dir_path_str: str, extension: str) -> None: ...
45
+
46
+ # Helper registration.
47
+ def register_helper(self, name: str, helper_fn: Callable[[str], str]) -> None: ...
48
+
49
+ # Template management.
50
+ def has_template(self, name: str) -> bool: ...
51
+ def unregister_template(self, name: str) -> None: ...
52
+
53
+ # Rendering.
54
+ def render(self, name: str, data_json: str) -> str: ...
55
+ def render_template(self, template_str: str, data_json: str) -> str: ...
56
+
57
+ # Extra helper registration.
58
+ def register_extra_helpers(self) -> None: ...
handlebarrz/py.typed ADDED
File without changes