|
| 1 | +# Copyright © 2023 Innovatie Ltd. All rights reserved. |
| 2 | +""" |
| 3 | +Jinja support. |
| 4 | +""" |
| 5 | +importtypingast |
| 6 | + |
| 7 | +fromjinja2importpass_context |
| 8 | +fromjinja2.extimportExtension |
| 9 | +fromjinja2.runtimeimportContext,Undefined |
| 10 | + |
| 11 | + |
| 12 | +classReactPyExtension(Extension): |
| 13 | +""" |
| 14 | + Jinja has more expressive power than core Django's templates, and can |
| 15 | + directly handle expansions such as: |
| 16 | +
|
| 17 | + {{ component(*args, **kwargs) }} |
| 18 | + """ |
| 19 | +# |
| 20 | +# Therefore, there is no new tag to parse(). |
| 21 | +# |
| 22 | +tags= {} |
| 23 | + |
| 24 | +def__init__(self,environment): |
| 25 | +super().__init__(environment) |
| 26 | +# |
| 27 | +# All we need is to add global "component" to the environment. |
| 28 | +# |
| 29 | +environment.globals["component"]=self._component |
| 30 | + |
| 31 | +@pass_context |
| 32 | +def_component(self,__context:Context,implementation:str,*args:t.Any, |
| 33 | +**kwargs:t.Any)->t.Union[t.Any,Undefined]: |
| 34 | +""" |
| 35 | + This method is used to embed an existing ReactPy component into your |
| 36 | + Jinja2 template. |
| 37 | +
|
| 38 | + Args: |
| 39 | + implementation: String of the fully qualified name of a component. |
| 40 | + *args: The component's positional arguments. |
| 41 | + **kwargs: The component's keyword arguments. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + Whatever the components returns. |
| 45 | + """ |
| 46 | +module,name=implementation.rsplit('.',1) |
| 47 | +component=getattr(__import__(module,None,None, [name]),name) |
| 48 | +template_args=component(*args,**kwargs).render() |
| 49 | +# |
| 50 | +# TODO: template_args looks like this: |
| 51 | +# |
| 52 | +# {'tagName': 'h1', 'children': ['Hello World!']} |
| 53 | +# |
| 54 | +# and need to be run through the Django template in |
| 55 | +# templates/reactpy/component.html, or equivalent. |
| 56 | +# |
| 57 | +returntemplate_args |