【发布时间】:2014-04-22 15:10:51
【问题描述】:
检查 django-crispyforms 的 bootstrap3 模板包中的 field.html 模板,我注意到引用了一个额外的上下文变量“tag”。您可以在模板的line 12 和line 41 上看到这一点。如何在用于呈现特定表单字段的 field.html 模板的上下文中为“tag”指定一个值?
【问题讨论】:
检查 django-crispyforms 的 bootstrap3 模板包中的 field.html 模板,我注意到引用了一个额外的上下文变量“tag”。您可以在模板的line 12 和line 41 上看到这一点。如何在用于呈现特定表单字段的 field.html 模板的上下文中为“tag”指定一个值?
【问题讨论】:
我使用palestamp 的回复作为指南来构建更通用的CustomCrispyField。您可以将extra_context 作为kwarg 传递给CustomCrispyField。 extra_context 只是我在从crispy_forms 复制的自定义模板中访问的字典。
from crispy_forms.layout import Field
from crispy_forms.utils import TEMPLATE_PACK
class CustomCrispyField(Field):
extra_context = {}
def __init__(self, *args, **kwargs):
self.extra_context = kwargs.pop('extra_context', self.extra_context)
super(CustomCrispyField, self).__init__(*args, **kwargs)
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs):
if self.extra_context:
extra_context = extra_context.update(self.extra_context) if extra_context else self.extra_context
return super(CustomCrispyField, self).render(form, form_style, context, template_pack, extra_context, **kwargs)
我会在我的表单中这样使用它:
self.helper.layout=Div(CustomCrispyField('my_model_field', css_class="col-xs-3", template='general/custom.html', extra_context={'css_class_extra': 'value1', 'caption': 'value2'})
我的模板将包含类似于以下的代码:
{% crispy_field field %}
<button class="btn {{ css_class_extra }}">{{ caption }}</button>
【讨论】:
您可以像这样覆盖标准的脆皮字段:
class LinkField(Field):
def __init__(self, *args, **kwargs):
self.view_name = kwargs.pop('view_name')
super(LinkField, self).__init__(*args, **kwargs)
def render(self, form, form_style, context, template_pack=CRISPY_TEMPLATE_PACK):
if hasattr(self, 'wrapper_class'):
context['wrapper_class'] = self.wrapper_class
if hasattr(self, 'view_name'):
context['view_name'] = self.view_name
html = ''
for field in self.fields:
html += render_field(field, form, form_style, context, template=self.template, attrs=self.attrs, template_pack=template_pack)
return html
然后只需在覆盖的模板中传递附加变量('view_name')。
在布局中它看起来像这样:
Layout(
LinkField('field_name', template='path_to_overridden_template',
view_name='variable_to_pass')
)
【讨论】:
tag 上下文变量是在模板中设置的,而不是在视图中设置的。如果您使用的是内置 bootstrap3 模板包,则它在包含field.html 的模板中定义。如果包含模板未定义tag,则默认为div。
例如:table_inline_formset.htmlline 41。
【讨论】:
根据 bobort 的回答,我想强调一下,您因此可以使用任何查询集作为 extra_content 中的参数,这允许您通过自定义模板注入您想要的任何内容的 html 呈现,这成为关于如何将酥脆的形式变成超级敏捷。我目前正在使用表单来呈现我的模板,而不是在模板中呈现表单^^
【讨论】: