将类添加到Django label_tag()输出 [英] Add class to Django label_tag() output

查看:940
本文介绍了将类添加到Django label_tag()输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些方法来为表单字段的label_tag()方法的输出添加一个类属性。



我看到有能力传递一个attrs字典,我已经在shell中进行了测试,我可以这样做:

 表单中的字段:
print field.label_tag(attrs {'class':'Foo'})

我将在我的输出中看到class ='Foo',但是我没有看到从模板中添加attrs参数的方法 - 实际上,模板是专门设计的,不是吗?



我的表单定义有一种方法来定义要在标签中显示的类?



在表单中,我可以执行以下操作来输入一个类

  self.fields ['some_field']。widget.attrs ['class'] ='Foo'

我只需要输出类。

解决方案

A 自定义模板标签似乎是解决方案。自定义过滤器也可以做,尽管它可以不太优雅。但是,在这两种情况下,您都需要回到自定义表单渲染。



如果这是一个非常重要的任务,我将创建一个Mixin,让我用标签类和表单渲染方法使用这些类来注释表单域。以下代码的作用如下:

  {{form.as_table_with_label_classes}} 
/ pre>

但我想问一下;你真的需要一个类标签标签吗?我的意思是HTML设计。在这里添加一个类是绝对必要的不能用一些CSS来解决,如:

  encapsulationulating_selector label {
some-attr:some-value;
}

我有时使用 jQuery 对于这种情况,其中;如果它不起作用,它将改善页面,但如果不则不会是灾难。并保持HTML源尽可能精简。


I need some way to add a class attribute to the output of the label_tag() method for a forms field.

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'})

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'

I just need to have it output the class for the as well.

解决方案

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.

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 }}

But I'd like to ask; Do you really need a class on the label tag? I mean HTML design-wise. It is absolutely necessary to add a class in there? Couldn't it be solved with some CSS like:

encapsulating_selector label {
    some-attr: some-value;
}

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()输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆