Login

Field List Tag

Author:
hughsaunders
Posted:
May 3, 2011
Language:
Python
Version:
Not specified
Tags:
properties field iterate
Score:
0 (after 0 ratings)

Tag for iterating through the fields of an object from a template.

The tag is passed two string arguments, the name of the model to use (which is then looked up in the context dictionary), and the format string. The format string should include two string place holders.

The tag will output each field name and value according to the format string supplied.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import re
from django import template

register=template.Library()

class PropertyListNode(template.Node):
    def __init__(self,model_string,format_spec):
        self.model_string=model_string
        self.format_spec=format_spec
    def render(self,context):
        model_instance=context[self.model_string]
        out=""
        for field in model_instance.__class__._meta.fields:
            try:
                out+=self.format_spec%\
                    (field.verbose_name,
                     getattr(model_instance,field.name))
            except TypeError as e:
                raise template.TemplateSyntaxError("invalid format string\
                        specified  to property list template tag: "+str(e))
        return out


def property_list(parser,token):
    """Property list tag, returns all fields of a model in the order defined,
    using a format specifier passed to the tag. 

    Example usage {% property_list car
    "<li><span>%s:</span><span>%s</span></li>" %}"""
    try:
        tag_name, model,format_spec=token.split_contents()
        #remove quotes from format_spec string
        format_spec=re.sub("\"","",format_spec)
    except ValueError:
        raise template.TemplateSyntaxError("%r tag requires model\
 and format string arguments only"%token.contents.split()[0])
    return PropertyListNode(model,format_spec) 


register.tag('property_list',property_list)

More like this

  1. Simple template tag to do |stringformat filter with format from a variable by leopd 4 years, 1 month ago
  2. date range by mackenzie_kearl 7 years, 3 months ago
  3. simple tag-cloud Template Tag by metty 5 years, 8 months ago
  4. Hierarchical Flatpage Tag by 0sn 6 years, 6 months ago
  5. Changing the look of newforms as_table with a custom BaseForm by bikeshedder 7 years, 11 months ago

Comments

Please login first before commenting.