首頁  >  文章  >  後端開發  >  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