在Python中重构HTML
项目描述
phtml是一个愚蠢的Python库,用于在Python中生成HTML,就像使用模板一样,但基于嵌套组件的Pythonic React-like模式,以重构为导向。
组件基础
基本组件类是Node
from phtml import Node
form_layout = Node(
'form', # node.tag
{ # node.attrs
'class': 'foo', # node.attrs['class']
'method': 'POST', # node.attrs['method']
},
[ # node.children
'{{ form.as_p() }}', # node.children[0]
Node('input', {'type': 'submit'}, selfclose=True),
],
)
Casting form_layout to string will return the following
<form class="foo" method="POST">
{{ form.as_p() }}
<input type="submit" />
</form>
渲染
While calling phtml.jinja.render(form_layout, form=YourForm()) will return the phtml output processed with form in the context and produce the final result.
整个目的就是将HTML生成逻辑重构到Python组件中
from phtml import Form, Submit
form_layout = Form(
{'class': 'foo'},
['{{ form.as_p() }}', Submit())],
)
动态导入
from phtml import Node
form_layout = Node.factory(
'phtml.Form', {'class': 'foo'},
['{{ form.as_p() }}', Node('phtml.Submit')],
)
Jinja和Materialize for the poor
假设您想为登录表单制作一个漂亮的布局,请不要重复无聊且冗长的代码,因为在这个世界的某个地方,一只猫可能会因为另一个现实中的副作用而死
from phtml import Form, Div
your_layout = Form(
Div({'class': 'row'}, [
Div({'class': 'col m6 s12'}, ['{{ form["username"] }}']),
Div({'class': 'col m6 s12'}, ['{{ form["password"] }}']),
]),
)
为富有的人重构组件
而是使用可重用的组件制作一个漂亮的布局
from phtml.django.mdc import Form, Row, Col, Input
class YourLoginForm(forms.LoginForm):
_phtml = Form(
Row(
Col(m=6, s=12, Input('username')),
Col(m=6, s=12, Input('password')),
)
)
愚蠢且愚蠢的基于上下文的渲染
您可以在jinja(或在没有花括号的Python中)中如此渲染:{{ form._phtml.jinja(form) }},因为所有的渲染逻辑都应该已经在phtml中。
感谢
非常感谢您的阅读。希望这将为那些致力于“在Python中重构HTML”的人提供有用的示例。
项目详细信息
关闭
phtml-0.0.1.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | c8503b1ecdf4a67fd31ba7f43d7b6de18ce7c249ca279aefa0dab2a9342f61e8 |
|
MD5 | d52afd2ef22cc25e65235f1fad528757 |
|
BLAKE2b-256 | c82f9c2ff4317d3f0bd773273aba4e0f96036f66b85212038882ee17df39253e |