我设置了一个工作的自定义模板标签,它已注册,我可以调用它,它实例化一个 template.Node 实例并调用它的 render() 方法。问题是当我返回一个简单的字符串时
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