2011-11-17 79 views

回答

20

內置的方法是用templatetag模板標籤(https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#templatetag)手動轉義每個模板項目,但我懷疑這不是你想要做的。

你真正想要的是一種將整塊標記爲原始(而不是可解釋)文本的方法,這需要一個新的自定義標記。您可能要檢查出raw標籤瀏覽:http://www.holovaty.com/writing/django-two-phased-rendering/

編輯:由於Django的1.5,這是現在所處理的內置verbatim模板標籤

5

有一對夫婦公開售票來解決這個問題: https://code.djangoproject.com/ticket/14502https://code.djangoproject.com/ticket/16318 您可以在下面找到一新的模板標籤verbatim

""" 
From https://gist.github.com/1313862 
""" 

from django import template 

register = template.Library() 


class VerbatimNode(template.Node): 

    def __init__(self, text): 
     self.text = text 

    def render(self, context): 
     return self.text 


@register.tag 
def verbatim(parser, token): 
    text = [] 
    while 1: 
     token = parser.tokens.pop(0) 
     if token.contents == 'endverbatim': 
      break 
     if token.token_type == template.TOKEN_VAR: 
      text.append('{{') 
     elif token.token_type == template.TOKEN_BLOCK: 
      text.append('{%') 
     text.append(token.contents) 
     if token.token_type == template.TOKEN_VAR: 
      text.append('}}') 
     elif token.token_type == template.TOKEN_BLOCK: 
      text.append('%}') 
    return VerbatimNode(''.join(text)) 
+0

我想'raw'標籤比這些的一個更好的解決方案。加'verbatim'不處理註釋標記和'noparse'返回和空字符串。 – Jake

+2

如果您覺得這樣,您應該確保對相關的門票發表評論。這是社區決定哪些功能將進入Django。我並不是說這是做這件事的最好方式,但這是社羣目前正在採取的行動。 –

+0

仔細觀察,很明顯,noparse會遍歷塊中的令牌,並將它們全部設置爲文本令牌。 – Jake