我需要检索保存在DB中的可选号码到我制作的自定义模板标签。要检索的是此图库中包含的变量(照片ID)。在画廊循环中。
{% get_latest_photo {{photo.id}} %}
如何实现?!
P.s:我知道可以用包含标签来完成,但是现在如何解决这个问题呢!
编辑模板html文件:
{% 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当我将album.id(在{%get_latest_photo photo.id%}中)替换为一个作为专辑ID并从中检索照片的数字时,它的效果非常好。
此致 H. M.
答案 0 :(得分:8)
在模板标签中使用时,不要将括号括在变量周围。
{% get_latest_photo photo.id %}
答案 1 :(得分:5)
要正确评估 num 变量,我认为您应该像这样修改 LatestPhotoNode 类:
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 ''
答案 2 :(得分:3)
您确定您的模板标签写得正确吗?例如,您需要使用Variable.resolve来正确获取变量的值:Passing Template Variables to the Tag
答案 3 :(得分:1)
我遇到了同样的问题,在reading the docs之后,我使用此
解决了问题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 ''
如果您尝试渲染多个变量,使用json.dumps
非常有用。