【问题标题】:Django-Template : Get Variables in a Tag block !Django-Template:在标签块中获取变量!
【发布时间】:2010-11-19 03:35:36
【问题描述】:

我需要检索一个保存在 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 %}

模板标签

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.

【问题讨论】:

  • 如果您告诉我们代码的异常行为,我们将更容易为您提供答案。
  • 能贴出标签的代码吗?

标签: django templates django-templates


【解决方案1】:

在模板标签中使用变量时,不要用括号括起来。

{% get_latest_photo photo.id %}

【讨论】:

  • 在我添加括号之前尝试过,但根本没有用!
【解决方案2】:

要正确评估 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 ''

【讨论】:

  • 如何使用过滤值?比如{% url_parameter tags=tag|slugify %}
  • self.variable 是什么?
【解决方案3】:

你确定你的模板标签写得正确吗?比如需要使用Variable.resolve来正确获取变量的值:Passing Template Variables to the Tag

【讨论】:

  • 你好 Ned,如何使用 Variable.resolve,我现在正在搜索,你能给我一个例子吗?!
  • 只是一个经典的自定义模板标签,它将过滤照片并获取添加到此相册的最新照片。我编辑了主要问题。
  • 嗯,很快就会做,但不知何故,我相信自定义模板标签不是问题,因为当我用数字替换 photo.id 并用相册过滤照片时,它工作得很好。身份证!
  • 你好内德,我用这个codespatter.com/2009/01/22/how-to-write-django-template-tags修复了它。谢谢
【解决方案4】:

我遇到了同样的问题,在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 非常有用。

【讨论】:

    猜你喜欢
    • 2016-11-21
    • 2013-07-23
    • 2016-05-30
    • 1970-01-01
    • 2017-02-27
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多