views:

1106

answers:

3

Hello,

I need to retrieve an optional number saved in DB , to a custom template tag i made . which to retrieve , a variable ( a photo ID ) included in this Gallery . within the gallery loop .

{% get_latest_photo   {{photo.id}}  %}

How to accomplish that ?!

P.s : I know that can be done with inclusion tag , but in the present time how to make it fix this one !

Edit the template html file :

{% for album in albumslist %}

    {% get_latest_photo   photo.id  %} 
    {% for photo in recent_photos %}
<img src='{% thumbnail photo.image 200x80 crop,upscale %}' alt='{{ photo.title }}' />
    {% endfor %}
    {{ album.title }}
{% endfor %}

templatetag

from django.template import Library, Node
from akari.main.models import *
from django.db.models import get_model

register = Library()

class LatestPhotoNode(Node):
    def __init__(self, num):
     self.num = num
    def render(self, context):
     photo = Photo.objects.filter(akar=self.num)[:1]
     context['recent_photos'] = photo
     return ''

def get_latest_photo(parser, token):
    bits = token.contents.split()
    return LatestPhotoNode(bits[1])

get_latest_photo = register.tag(get_latest_photo)

P.s Its working very well when i replace album.id (in {% get_latest_photo photo.id %} ) with a number which acts as an album id and retrieve the photo from .

Regards H. M.

+4  A: 

You don't put the brackets around variables when you use them in template tags.

{% get_latest_photo photo.id %}
Steve Losh
tried that before i add the brackets but didn't work at all !
Hamza
Thank you fixed it :)
Hamza
+2  A: 

Are you sure your template tag is written properly? For example, you need to use Variable.resolve to properly get the values of variables: Passing Template Variables to the Tag

Ned Batchelder
Hello Ned , How to use Variable.resolve , am searching about that now , can you link me an example please ?!
Hamza
Just a classic custom template tag which will filter the photos and get the latest photo added with this album . i Edited the main Question .
Hamza
Hmm ,WIll do soon , but somehow i believe the Custom Template tag is not the problem , cause it works very fine when i replace the photo.id with a number with filter the Photo with the album.id !
Hamza
Hello Ned , i fixed it using this http://codespatter.com/2009/01/22/how-to-write-django-template-tags/ .Thank You
Hamza
+2  A: 

To evaluate correctly the num variable I think you should modify your LatestPhotoNode class like this:

class LatestPhotoNode(Node):
    def __init__(self, num):
        self.num = template.Variable(num)

    def render(self, context):
        num = self.variable.resolve(self.num)
        photo = Photo.objects.filter(akar=num)[:1]
        context['recent_photos'] = photo
        return ''
Pierre-Jean Coudert
Thank you , already fixed it using this . its simple
Hamza