Django 1.4自定义模板标签返回HTML

时间:2012-05-28 12:56:59

标签: django templates

我设置了一个工作的自定义模板标签,它已经注册,我可以调用它,它实例化一个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

1 个答案:

答案 0 :(得分:7)

我认为您的问题是您需要在模板中使用...|safe告诉django将此结果显示为html,而不是强制将其显示为"..."

的字符串

https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#safe