首页  >  文章  >  后端开发  >  django-components v 模板现在与 Vue 或 React 相当

django-components v 模板现在与 Vue 或 React 相当

Barbara Streisand
Barbara Streisand原创
2024-09-26 06:58:22372浏览

django-components v Templating is now on par with Vue or React

嘿,我是 Juro,我是 django-components 的维护者之一。在版本 v0.90-0.94 中,我们添加了一些功能,使在模板中使用组件更加灵活,类似于 JSX / Vue。

(此信息已经有点过时了(一个月前发布;最新的是 v0.101),因为我正忙于添加对 JS / CSS 变量、TypeScript 和 Sass 以及 HTML 片段的支持。令人兴奋的东西!但我意识到还没有分享此更新!)

无论如何,以下是一个组件 blog_post,它接受从 blog_post_props 应用的标题、id 和附加 kwargs:

    {% blog_post
      title="{{ person.first_name }} {{ person.last_name }}"
      id="{% random_int 10 20 %}"
      ...blog_post_props
    / %}

以上是多个特征的组合:

1。自关闭标签:

而不是

    {% component "my_component" %}
    {% endcomponent %}

您现在可以简单地写

    {% component "my_component" / %}

2。多行标签:

django_components 现在自动配置 Django 以允许多行标签。因此,不要将所有内容都塞在一行中:

    {% component "blog_post" title="abcdef..." author="John Wick" date_published="2024-08-28" %}
    {% endcomponent %}

您可以将其分散到多行中:

    {% component "blog_post"
      title="abcdef..."
      author="John Wick"
      date_published="2024-08-28"
    / %}

3。展开运算符:

类似于 JSX 中的 ...props 运算符或 Vue 中的 v-bind,这会将 props / kwargs 插入给定位置。

所以代替

    {% component "blog_post"
      title="abcdef..."
      author="John Wick"
      date_published="2024-08-28"
    / %}

你可以将 kwargs 放入字典中,然后应用它:

    # Python
    props = {
        "title": "abcdef...",
        "author": "John Wick",
        "date_published": "2024-08-28"
    }
    {# Django #}
    {% component "blog_post" ...props %}

4。组件输入中字符串文字内的模板标签:

您现在可以在组件输入中使用模板标签和过滤器:

    {% component 'blog_post'
      "As positional arg {# yay #}"
      title="{{ person.first_name }} {{ person.last_name }}"
      id="{% random_int 10 20 %}"
      readonly="{{ editable|not }}"
    / %}

这样您就不必每次需要格式化值时都定义额外的变量。

请注意,当只有一个标签并且周围没有额外的文本时,结果将作为值传递。所以“{% random_int 10 20 %}”传递一个数字,“{{ editable|not }}”传递一个布尔值。

您甚至可以更进一步,获得与 Vue 或 React 类似的体验,您可以在其中评估任意代码表达式,又名类似于:

    <MyForm
      value={ isEnabled ? inputValue : null }
    />

这可以通过 django-expr 实现,它添加了一个 expr 标签和过滤器,您可以使用它来计算模板中的 Python 表达式:

    {% component "my_form"
      value="{% expr 'input_value if is_enabled else None' %}"
    / %}

5。支持 {% comp_name %} {% endcomp_name %} 和 TagFormatter

默认情况下,组件是使用组件标签编写的,后跟组件的名称:

    {% component "button" href="..." disabled %}
        Click me!
    {% endcomponent %}

您现在可以更改此设置(甚至可以自己制作!)。

例如,将 COMPONENTS.tag_formatter 设置为“django_components.shorthand_component_formatter”允许您编写如下组件:

    {% button href="..." disabled %}
        Click me!
    {% endbutton %}

还有更多功能即将推出,所以一定要尝试一下 django-components!

以上是django-components v 模板现在与 Vue 或 React 相当的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn