Django - 如何向模板中的表单添加html属性 [英] Django - How to add html attributes to forms on templates

查看:657
本文介绍了Django - 如何向模板中的表单添加html属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下模板:

 < div id =openid_input_area> 
{{form.openid_identifier}}
< input name =bsignintype =submitvalue ={%trans登录%}>
< / div>

如何添加一个css类到form.openid_identifier?



由于我坚持 SOC 原则,我期望设计者改进我所做的模板想在表单模型上执行此操作,但在模板本身。



我在文档上找不到任何内容。有没有办法在模板上这样做?

解决方案

我已经设法为我的问题编写了一个简单的解决方案: / p>

我写了一个自定义模板标签

 从django导入模板

register = template.Library ()

def htmlattributes(value,arg):
attrs = value.field.widget.attrs


data = arg.replace(' ','')

kvs = data.split(',')

用于kvs中的字符串:
kv = string.split(':')
attrs [kv [0]] = kv [1]

rendered = str(value)

返回渲染

注册。过滤器('htmlattributes',htmlattributes)

所有我必须在模板中做的是: p>

  {{form.openid_identifier | htmlattributes:class:something,id:openid_identi fier}} 


Suppose I have the following template:

<div id="openid_input_area">
{{ form.openid_identifier }}
    <input name="bsignin" type="submit" value="{% trans "Sign in" %}">
</div>

How can I add a css class to form.openid_identifier?

As I am adhering to the SOC principles and I expect designers to improve the templates I do NOT want to do this on the form model but on the template itself.

I couldn't find anything on this on the docs. Is there a way to do this on the template?

解决方案

I've managed to code a simple solution to my problem:

I wrote a 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)

And all I have to do at the template is:

{{ form.openid_identifier|htmlattributes:"class : something, id: openid_identifier" }}

这篇关于Django - 如何向模板中的表单添加html属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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