Django-Template : Get Variables in a Tag block !

前端 未结 4 570
有刺的猬
有刺的猬 2021-02-04 14:37

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

相关标签:
4条回答
  • 2021-02-04 14:48

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

    {% get_latest_photo photo.id %}
    
    0 讨论(0)
  • 2021-02-04 14:54

    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 ''
    
    0 讨论(0)
  • 2021-02-04 15:01

    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

    0 讨论(0)
  • 2021-02-04 15:07

    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.

    0 讨论(0)
提交回复
热议问题