跳转到主要内容

在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 (4.0 kB 查看哈希值)

上传时间