IT

템플릿 변수를 HTML로 렌더링

lottoking 2020. 5. 27. 07:55
반응형

템플릿 변수를 HTML로 렌더링


'messages'인터페이스를 사용하여 다음과 같이 사용자에게 메시지를 전달합니다.

request.user.message_set.create(message=message)

{{ message }}변수에 html을 포함 시키고 템플릿에서 마크 업을 피하지 않고 렌더링하고 싶습니다 .


HTML을 이스케이프하지 않으려면 safe필터와 autoescape태그를 확인하십시오.

safe:

{{ myhtml |safe }}

autoescape:

{% autoescape off %}
    {{ myhtml }}
{% endautoescape %}

텍스트로 더 복잡한 것을 원한다면 html을 반환하기 전에 자신의 필터를 만들고 마술을 할 수 있습니다. templatag 파일은 다음과 같습니다.

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

register = template.Library()

@register.filter
def do_something(title, content):

    something = '<h1>%s</h1><p>%s</p>' % (title, content)
    return mark_safe(something)

그런 다음 템플릿 파일에 추가 할 수 있습니다

<body>
...
    {{ title|do_something:content }}
...
</body>

그리고 이것은 당신에게 좋은 결과를 줄 것입니다.


를 사용하여 autoescapeHTML 이스케이프 기능을 해제하십시오.

{% autoescape off %}{{ message }}{% endautoescape %}

코드에서 템플릿을 다음과 같이 렌더링 할 수 있습니다.

from django.template import Context, Template
t = Template('This is your <span>{{ message }}</span>.')

c = Context({'message': 'Your message'})
html = t.render(c)

자세한 내용은 Django 문서참조하십시오 .


가장 간단한 방법은 safe필터 를 사용하는 것입니다 .

{{ message|safe }}

자세한 내용 은 안전 필터에 대한 장고 설명서를 확인 하십시오.


템플릿에서 필터 또는 태그를 사용할 필요가 없습니다. format_html ()을 사용하여 변수를 html로 번역하면 Django가 자동으로 이스케이프를 해제합니다.

format_html("<h1>Hello</h1>")

https://docs.djangoproject.com/en/1.9/ref/utils/를 확인 하십시오.

참고 URL : https://stackoverflow.com/questions/4848611/rendering-a-template-variable-as-html

반응형