如果你實際上是在文本字段中存儲引用,就像這樣,那麼本質上你使用一種簡單的標記語言來存儲引用。
在這種情況下,我認爲模板應該是這樣做的地方。
不幸的是,我不知道有什麼方法可以創建過濾器並寫入上下文變量。因此,而不是使用過濾器,你將有,像使用一個標籤:
{% output_with_references article_content myreferencesvar %}
[snip]
<ul>
{% for ref in myreferencesvar %}
<li><a name="{{ ref.id }}">{{ ref.authors }}, {{ ref.year }}</a></li>
{% endif %}
</ul>
BTW:如果有是同時使用過濾器寫入頁面上下文的方式,我d愛知道它。
更新
要實現它,你會使用類似:
from django.template import Library, Node, TemplateSyntaxError
register = Library()
class OutputWithReferencesNode(Node):
def __init__(self, input, ref_varnam='references'):
self.input = input
self.ref_varnam=ref_varnam
def render(self, context):
output = self.input
references = []
# process self.input
context[self.ref_varnam] = references
return output
@register.tag
def output_with_references(parser, token):
try:
fnctn, input, ref_varname = token.split_contents()
except ValueError:
raise TemplateSyntaxError, "%s takes the syntax %s text_to_output references_variable_name" % (fnctn,)
return OutputWithReferencesNode(input, ref_varname)
您好,感謝您的答覆,所以才確認:outputwithreferences應該創建myreferencesvar(參數1 =有標記文本,參數2是一個新的變量?),然後可以在頁面之後使用? – 2010-12-06 19:40:36