Django-Template:在Tag块中获取变量!

Ham*_*mza 9 django templates django-templates

我需要检索保存在DB中的可选号码到我制作的自定义模板标签.要检索的是此图库中包含的变量(照片ID).在画廊循环内.

{% get_latest_photo   {{photo.id}}  %} 
Run Code Online (Sandbox Code Playgroud)

怎么做到这一点?!

Ps:我知道可以用包含标签来完成,但是现在如何解决这个问题!

编辑模板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 %}
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

Ps当我将album.id(在{%get_latest_photo photo.id%}中)替换为一个作为专辑ID并从中检索照片的数字时,它的效果非常好.

关心HM

Ste*_*osh 8

在模板标记中使用括号时,不要将括号括在变量周围.

{% get_latest_photo photo.id %}
Run Code Online (Sandbox Code Playgroud)


Pie*_*ert 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 ''
Run Code Online (Sandbox Code Playgroud)