2009-08-12 24 views
9

我需要檢索保存在數據庫中的可選編號,以製作我自定義的模板標籤。它將檢索包含在此圖庫中的變量(照片ID)。在畫廊循環內。Django-Template:在變量塊中獲取變量!

{% get_latest_photo {{photo.id}} %} 

如何做到這一點? P:我知道可以用包含標籤來完成,但是現在如何使它修復這個問題!

編輯模板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) 

詩及其與一些工作得很好,當我更換album.id(在{%get_latest_photo photo.id%})它充當專輯ID並從中檢索照片。

問候 H. M.

+0

如果您告訴我們代碼的錯誤行爲,我們會更容易給您答案。 – 2009-08-13 01:40:01

+0

你可以發佈標籤的代碼嗎? – 2009-08-13 02:17:16

回答

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 '' 
+0

謝謝,已經使用它修復了它。其簡單的 – Hamza 2009-08-16 12:50:59

+0

你如何使它與過濾的值一起工作?就像'{%url_parameter tags = tag | slugify%}'一樣 – tutuca 2011-03-22 02:48:53

8

你不要把括號變量,當你在模板標籤中使用它們。

{% get_latest_photo photo.id %} 
+0

在我添加括號之前嘗試過,但根本沒有工作! – Hamza 2009-08-13 00:51:49

+0

謝謝修復:) – Hamza 2009-08-13 04:43:45

3

您確定您的模板標籤是否正確書寫?例如,你需要使用Variable.resolve正確獲取變量的值:Passing Template Variables to the Tag

+0

Hello Ned, 如何使用Variable.resolve,我現在正在尋找,你能鏈接我一個例子嗎?! – Hamza 2009-08-13 01:43:57

+0

只是一個經典的自定義模板標籤,它將過濾照片並獲取隨該相冊添加的最新照片。我編輯了主要問題。 – Hamza 2009-08-13 01:48:48

+0

嗯, 很快,但不知怎的,我相信自定義模板標籤不是問題,因爲它工作得很好,當我用一個數字替換photo.id並用album.id過濾照片! – Hamza 2009-08-13 02:22:56

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 '' 

如果你正在嘗試仁der多個變量,使用json.dumps非常有用。