django_slots = 包含标签 + 块
项目描述
django_slots
允许捕获多行字符串并将其传递到模板标签。
演示
- 注册组件
# app/templatetags/component_tags.py
from django_slots import Library, Component
register = Library()
@register.block_component
class Details(Component):
pass
- 创建模板
{# app/templates/components/details.html #}
<details>
<summary>{{ summary|default:slots.summary }}</summary>
{{ slot }}
</details>
使用方法
{% load component_tags %}
{% load slot_tags %}
{% details summary="the summary" %}
the default slot
{% /details %}
{% details %}
{% slot summary %}the <b>summary</b>{% /slot %}
the default slot
{% /details %}
安装
pip install django-slots
INSTALLED_APPS = [
# ...
'django_slots',
]
插槽
使用{% slot name %}{% /slot %}
来捕获并命名一个插槽。这些插槽将作为名为slots
的字典在模板中可用。例如{{ slots.name }}
。
任何没有被插槽标签包围的行将作为{{ slot }}
在组件模板中可用。
模板
默认的模板路径是components/<component_name>.html
。
使用template_name
属性或get_template_name()
方法来覆盖。
更改名称
默认情况下,模板标签的名称将是Component类名称转换为蛇形。使用name
属性来覆盖。
例如
from django_slots import Component, Library
register = Library()
@register.inline_component
class Button(Component):
name = 'btn'
{% btn %}
更改名称格式
默认情况下,内联标签的名称是"{name}/"
,块标签的名称是"{name}", "/{name}"
。要更改此格式,请指定inline_tag_name
和block_tag_names
属性。
例如
from django_slots import Component, Library
register = Library()
class AppComponent(Component):
inline_tag_name = "{name}end"
block_tag_names = "{name}", "end{name}"
@register.component
class Button(AppComponent):
pass
{% buttonend %}
{% button %}{% endbutton %}
仅内联模板标签
使用@register.inline_component
仅允许使用{% inline/ %}
。
仅块模板标签
使用@register.block_component
仅允许使用{% block %}{% /block %}
。
验证参数
实现def get_content_data(slots, **kwargs)
以验证参数。
例如
from django_slots import Component, Library
register = Library()
@register.component
class Button(Component):
STYLE = ["primary", "secondary"]
def get_context_data(self, slots, *, style: str):
if style not in self.STYLE:
raise self.validation_error(f"style {style!r} not in {self.STYLE!r}")
return super().get_context_data(slots, style=style)
命名空间组件
组件可以进行命名空间划分,这对于创建第三方应用非常有用。
from django_slots import Library, Component
register = Library()
class NHSUKComponent(Component):
namespace = 'nhsuk'
@register.component
class Button(NHSUKComponent):
pass
{% nhsuk:button %}
Save and continue
{% /nhsuk:button %}
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。
源分布
django_slots-0.2.7.tar.gz (5.3 kB 查看哈希值)
构建分布
django_slots-0.2.7-py3-none-any.whl (5.7 kB 查看哈希值)