0

私は初心者の django プログラマーで、Django テンプレート用の独自のテンプレート タグを作成したいと考えています。templatetags モジュールを作成しましたが、表示されているコードを使用すると正しく動作するようです。"&lt;"ただし、私の関数はand"&gt;"の代わりに"<"andを含む文字列を返します">"(関数の結果が関数によって変更されたかのようにaddslashes())。コードの何が問題になっていますか?

base_template.html (私のテンプレート タグを使用する django テンプレート)

<% load templatetags %>
<html>
 <head>
 </head>
 <body>
   {# text contains a string #}
   {{ text | formattedtext }}
 </body>
</html>

templatetags.py

from django import template

register = template.Library()
@register.filter(name='formattedtext')

def formattedtext(value):
    try:
        scoringTemplate = "<b>" + value + "</b>"
        print scoringTemplate #return string with "<b>text</b>"
        return scoringTemplate #however, this returns string with "&lt;text&gt;" value :(
    except ValueError:
        return value
    except:
        return value
4

1 に答える 1

2

出力を「安全」とマークする必要があります: https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.safestring.mark_safe

したがって、コードは次のようになります。

from django import template
from django.utils.safestring import mark_safe

register = template.Library()
@register.filter(name='formattedtext')

def formattedtext(value):
    try:
        scoringTemplate = "<b>" + value + "</b>"
        print scoringTemplate #return string with "<b>text</b>"
        return mark_safe(scoringTemplate)   # unescaped, raw html
    except ValueError:
        return value
    except:
        return value
于 2012-10-30T20:52:43.337 に答える