问题描述
我需要某种方法将类属性添加到表单字段的 label_tag()
方法的输出中.
I need some way to add a class attribute to the output of the label_tag()
method for a forms field.
我发现可以传入 attrs
字典,并且我已经在 shell 中对其进行了测试,我可以执行以下操作:
I see that there is the ability to pass in an attrs
dictionary and I have tested it in the shell and I can do something like:
for field in form:
print field.label_tag(attrs{'class':'Foo'})
我会在输出中看到 class='Foo'
,但我没有看到从模板中添加 attrs
参数的方法 - 事实上,模板是专门为此设计的,不是吗?
I will see the class='Foo'
in my output, but I don't see a way to add an attrs
argument from the template - in fact, templates are designed specifically against that, no?
我的表单定义中有没有办法定义要在标签中显示的类?
Is there a way in my form definition to define the class to be displayed in the label?
在表单中,我可以执行以下操作来给输入一个类
In the form, I can do the following to give the inputs a class
self.fields['some_field'].widget.attrs['class'] = 'Foo'
我只需要让它输出 <label/>
的类.
I just need to have it output the class for the <label />
as well.
推荐答案
A 自定义模板标签 似乎是解决方案.自定义过滤器也可以,尽管它可能不那么优雅.但在这两种情况下,您都需要回退到自定义表单呈现.
A custom template tag seems to be the solution. A custom filter would also do, although it can be less elegant. But you would need to fall back to custom form rendering in both cases.
如果这是一项非常重要的任务;我将创建一个 Mixin,它允许我使用标签类注释表单字段,并使用这些类提供表单呈现方法.使以下代码有效:
If this is a task of high importance; I'd create a Mixin that allows me to annotate the form fields with label classes and supplies form rendering methods using those classes. So that the following code works:
{{ form.as_table_with_label_classes }}
但是我想问一下;你真的需要标签标签上的类吗?我的意思是 HTML 设计明智.绝对有必要在那里添加一个类吗?难道不能用一些 CSS 来解决,比如:
But I'd like to ask; Do you really need a class on the label tag? I mean HTML design-wise. Is it absolutely necessary to add a class in there? Couldn't it be solved with some CSS like:
encapsulating_selector label {
some-attr: some-value;
}
我有时会使用 jQuery 来处理这种情况;如果它有效,它会改进页面,但如果它不起作用,它也不会是一场灾难.并尽可能精简 HTML 源代码.
I sometimes use jQuery for such cases where; it will improve the page if it works, but it won't be a disaster if it doesn't. And keep the HTML source as lean as possible.
这篇关于将类添加到 Django label_tag() 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!