2
我想知道是否有方法檢查標記是否有結束塊。我基本上是試圖讓用戶做django自定義標記內聯或塊
{% mytag 'a' 'b' 'c' %}
或
{% mytag 'a' 'b' 'c' %}
<!-- other markup here -->
{% end mytag %}
我看到如果它不存在它會引發異常,但有什麼辦法來編程設置我的標籤安全處理兩種情況?
我想知道是否有方法檢查標記是否有結束塊。我基本上是試圖讓用戶做django自定義標記內聯或塊
{% mytag 'a' 'b' 'c' %}
或
{% mytag 'a' 'b' 'c' %}
<!-- other markup here -->
{% end mytag %}
我看到如果它不存在它會引發異常,但有什麼辦法來編程設置我的標籤安全處理兩種情況?
您可以嘗試解析,直到結束標記並捕獲異常(如果未找到)。您可能要停止,如果你在運行也另mytag節點:如果
def do_mytag_stuff(parser, token):
# Process your token however you need
mytag_args = token.split_contents()
try:
nodelist = parser.parse(('endmytag', 'mytag'))
token = parser.next_token()
if token.contents == 'endmytag':
# Found an ending tag, make a node for its contents
parser.delete_first_token()
return MyTagNode(nodelist, mytag_args)
except TemplateSyntaxError:
# Neither tag was found
pass
# So either there's no closing tag, or we met another mytag before a closing tag.
# Do whatever you would for a single tag here
return SingleMyTagNode(mytag_args)
不知道這是100%正確的,但希望它會有所幫助。
我想我唯一的擔心是這可能掩蓋其他問題。就像沒有正確輸入內容的人一樣,包括DNE等的模板。 – Nix 2012-02-16 20:58:25
非常真實,我認爲只要有兩個類似的標籤會更清潔。 – 2012-02-16 21:55:38
這實際上可能是一個更好的解決方案,他們可以共享邏輯,所以它只是一個門面。 – Nix 2012-02-17 01:45:09