2010-12-06 26 views
0

我的Django模型有一個字段,我想在其中引用邏輯。舉個例子:這是否應該放在視圖邏輯中?

This is an example of text in the field.[ref type="quotation" name="Martin" date="2010"] 

當最終的標記呈現,這將呈現爲(減少爲例):

This is an example of text in the field.<a href="#ref">1</a> 
[SNIP] 
<ul> 
<li><a name="ref1">Martin, 2010</a></li> 
</ul> 

所以,從本質上講,我建立的參考列表進入一個不同{{}}進一步阻止頁面。

如果這種文本處理邏輯是在視圖中(所以我傳遞2值到模板,1是修改後的文本,1是參考表),還是有更多的Django式的方式通過過濾器等來做到這一點?

回答

1

如果你實際上是在文本字段中存儲引用,就像這樣,那麼本質上你使用一種簡單的標記語言來存儲引用。

在這種情況下,我認爲模板應該是這樣做的地方。

不幸的是,我不知道有什麼方法可以創建過濾器並寫入上下文變量。因此,而不是使用過濾器,你將有,像使用一個標籤:

{% 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) 
+0

您好,感謝您的答覆,所以才確認:outputwithreferences應該創建myreferencesvar(參數1 =有標記文本,參數2是一個新的變量?),然後可以在頁面之後使用? – 2010-12-06 19:40:36

相關問題