【问题标题】:is it possible to add a button with variable in templatetags是否可以在模板标签中添加一个带有变量的按钮
【发布时间】:2013-09-12 19:16:05
【问题描述】:

模板标签.py

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter("as_span")

def as_span(ZergitForm):
    ZergitForm_as_span = ZergitForm.as_ul().replace("<ul", "<span").replace("</ul", "</span")
    ZergitForm_as_span = ZergitForm_as_span.replace("<li", "<span").replace("</li", "</span")
    return mark_safe(ZergitForm_as_span)

我正在使用 MultipleChoiceField。使用此模板标签后,它在跨度而不是 &lt;li&gt; 标记中打印表单数据。我想对跨度内的每个数据执行删除操作。现在它正在打印每个 &lt;li&gt;单个&lt;span&gt;标签中的值。我需要为每个跨度插入一个输入按钮。

是否可以使用模板标签概念。

谢谢

【问题讨论】:

    标签: python django python-2.7 django-models django-templates


    【解决方案1】:

    您最好替换这些字段的小部件。似乎您正在使用CheckboxSelectMultiple,它使用&lt;ul&gt;&lt;li&gt;。创建一个继承自CheckboxSelectMultiple 的类并替换其render() 方法:

    (来自 django/forms/widgets.py)

    class CheckboxSelectMultiple(SelectMultiple):
        def render(self, name, value, attrs=None, choices=()):
            if value is None: value = []
            has_id = attrs and 'id' in attrs
            final_attrs = self.build_attrs(attrs, name=name)
            output = [u'<ul>']
            # Normalize to strings
            str_values = set([force_unicode(v) for v in value])
            for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
                # If an ID attribute was given, add a numeric index as a suffix,
                # so that the checkboxes don't all have the same ID attribute.
                if has_id:
                    final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                    label_for = u' for="%s"' % final_attrs['id']
                else:
                    label_for = ''
    
                cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
                option_value = force_unicode(option_value)
                rendered_cb = cb.render(name, option_value)
                option_label = conditional_escape(force_unicode(option_label))
                output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
            output.append(u'</ul>')
            return mark_safe(u'\n'.join(output))
    

    【讨论】:

      【解决方案2】:

      在渲染字段而不是整个表单时,您可以做类似的事情。

      如果你构建一个模板标签来呈现一个字段,你可以使用它的 id,你需要处理一个 ajax 调用来删除它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 2018-07-25
        • 2021-09-24
        • 2015-01-02
        • 1970-01-01
        • 2018-03-15
        相关资源
        最近更新 更多