Django-Template:在变量块中获取变量! [英] Django-Template : Get Variables in a Tag block !
问题描述
我需要检索保存在数据库中的一个可选编号,以及我制作的自定义模板标签。哪个要检索,这个图库中包含的变量(照片ID)。在图库循环中。
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}} %}
如何完成?
Ps:我知道可以包含标签,但在目前的时候如何使其修复这一个!
P.s : I know that can be done with inclusion tag , but in the present time how to make it fix this one !
编辑模板html文件:
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
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)
Ps当我用一个充当相册ID并从中检索照片的数字替换album.id(在{%get_latest_photo photo.id%})中时,它工作得很好。
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
HM
Regards H. M.
推荐答案
要正确评估 num 变量,我认为您应该修改 LatestPhotoNode 类: / p>
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 ''
这篇关于Django-Template:在变量块中获取变量!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!