Hey,
I have started to use Django (1.6) few weeks ago and I have the following problem to resolve by using templatetags. (this is my very first templatetags draft, so I may be wrong in the way of designing it, do not hesitate to highlight anything weird).
In my template, I have a list of elements (defined in the context) : items (among 6 different django models).
According to which class an item belongs, I have to display an image or a title specific to this class (these informations can't be stored in the models).
So basically, in my template I would like to have something like :
{% for item in items %}
<h1> {% show_title_tag item %} </h1>
<img>myPath/{% show_image_name_tag %}</img>
{% endfor %}
I can't have more than that.
@register.tag
def show_title_tag(parser,token):
tag_name, item = token.split_contents()
if isinstance(item,class1):
return MyNode(item.quote)
elif isinstance(item,class2):
return MyNode(item.subtitle)
elif isinstance(item,class3):
return MyNode(item.title)
...
# basically, the field to use change for each class
@register.tag
def show_image_name_tag(parser,token):
tag_name, item = token.split_contents()
if isinstance(item,class1):
return MyNode("specific image name linked to class 1")
elif isinstance(item,class2):
return MyNode("specific image name linked to class 2")
...
# the name change at each class, and is not stored in the object
class MyNode:
def __init__(self, image_or_title_string):
self.image_or_title_string = image_or_title_string
def render(self, context):
return image_or_title_string.resolve(context)
Two main questions :
1. I am duplicated the if-elif code. Any idea how I could do it without
duplicating it ? I could maybe only use one tag and add an extra
parameter (in the tag and in the render) to specify which
information I need (either the image or the title). Really not sure
about this ...
2. Can I have access to the variable and not the string in the tag code
(after doing : tag_name, item = token.split_contents()). I imagine
that item will be a string and not my django object. How can I
resolve this ?
Also, here are the requirements I have to enforce :
- keep template very simple
- use templatetags to solve it
- can't modify models
- check to which class an item belongs with a function as isinstance in
the templatetags (not in the template)
Please, any suggestions are welcome here, as long as they respect the requirements. Also, remind that I am a django beginner, I am just trying to do it simple and readable, not highly effective.
Thanks.