Hamza
Hamza

Reputation: 1533

Django-Template : Get Variables in a Tag block !

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.

Upvotes: 9

Views: 13603

Answers (4)

Chillar Anand
Chillar Anand

Reputation: 29534

I had the same problem problem and after reading the docs, I solved it using this

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

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

If you are trying to render multiple variables, using json.dumps is very useful.

Upvotes: 1

Pierre-Jean Coudert
Pierre-Jean Coudert

Reputation: 9347

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 ''

Upvotes: 5

Ned Batchelder
Ned Batchelder

Reputation: 375594

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

Upvotes: 3

Steve Losh
Steve Losh

Reputation: 19872

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

{% get_latest_photo photo.id %}

Upvotes: 8

Related Questions