假设我有以下模板:
<div id="openid_input_area">
{{ form.openid_identifier }}
<input name="bsignin" type="submit" value="{% trans "Sign in" %}">
</div>
如何向 form.openid_identifier 添加 css 类?
由于我遵守 SOC 原则,并且我希望设计人员改进模板,所以我不想希望在表单模型上执行此操作,而是在模板本身上执行此操作。
我在文档中找不到任何相关内容。有没有办法在模板上做到这一点?
最佳答案
我已经成功地为我的问题编写了一个简单的解决方案:
我写了一个custom template tag :
from django import template
register = template.Library()
def htmlattributes(value, arg):
attrs = value.field.widget.attrs
data = arg.replace(' ', '')
kvs = data.split(',')
for string in kvs:
kv = string.split(':')
attrs[kv[0]] = kv[1]
rendered = str(value)
return rendered
register.filter('htmlattributes', htmlattributes)
我在模板中要做的就是:
{{ form.openid_identifier|htmlattributes:"class : something, id: openid_identifier" }}
关于Django - 如何向模板上的表单添加 html 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4951810/