我設置了一個工作的自定義模板標記,它已註冊,我可以調用它,它實例化一個template.Node實例並調用其render()方法。問題是,當我返回一個簡單的字符串像Django 1.4自定義模板標記返回HTML
def render(self, context):
return 'asd'
它工作正常,但每當我試圖返回一個包含HTML的東西失敗:
def render(self, context):
return mark_safe('<ul class="jqueryFileTree" style="display: none;"><li><ITEM</li></ul>')
它靜靜地失敗,而無需渲染的事情。任何幫助?
編輯:增加了mark_safe。還不行的
編輯:標籤:
import os
import urllib
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
class DirTree(template.Node):
def __init__(self, start_dir):
self.start_dir = start_dir
def render(self, context):
# CODE THAT GENERATES A HTML NESTED LIST
return mark_safe('<ul class="jqueryFileTree"><li><ITEM</li></ul>')
@register.tag
def print_tree(parser, token):
try:
# split_contents() knows not to split quoted strings.
tag_name, start_dir = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires a single argument" % token.contents.split()[0])
if not (start_dir[0] == start_dir[-1] and start_dir[0] in ('"', "'")):
raise template.TemplateSyntaxError("%r tag's argument should be in quotes" % tag_name)
return DirTree(start_dir[1:-1])
# TEMPLATE.HTML
# HTML 'N STUFF
<div id="file-tree">
{% print_tree "catflow_portal/static/repo/usr/test-user/catalogs/food/" %}
</div>
#END TAGS
你不使用[mark_safe(https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.safestring.mark_safe)上返回前的字符串它呢? – jpic
仍然不起作用:\ – pistacchio
爲什麼不使用模板呢? – pyriku