Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.4 custom template tag return HTML

I set up a working custom template tag, it is registered, I can call it, it instantiates a template.Node instance and calls its render() method. The problem is that when I return a simple string like

def render(self, context):
    return 'asd'

it works ok, but it fails whenever i try to return something containing html:

def render(self, context):
    return mark_safe('<ul class="jqueryFileTree" style="display: none;"><li><ITEM</li></ul>')

it fails silently without rendering a thing. Any help?

EDIT: added mark_safe. Still doesn't work

EDIT: the tag:

    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
like image 780
pistacchio Avatar asked Feb 21 '23 08:02

pistacchio


1 Answers

I think your problem is you need to use ...|safe in your template to tell django to show this result as html, not force to show it as string with "..."

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

Update 2021-10-20: Django 3.2
...|safe Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect.

If you are chaining filters, a filter applied after safe can make the contents unsafe again. For example, the following code prints the variable as is, unescaped:
{{ var|safe|escape }}

https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#std:templatefilter-safe

like image 123
Pattapong J Avatar answered Feb 22 '23 20:02

Pattapong J