formatting table cell content in django-tables2

2020-08-05 11:05发布

Love django-tables... but something that I'm sure is trivial to solve is giving me fits. When the value I pass for a given row/column is like:

some<br/>random<br/>words<br/>returned

I want the browser to parse and render the content in that cell... to look like this:

some
random
words
returned

not escape the content I'm passing and display it like this:

some<br/>random<br/>words<br/>returned

Surely there's some flag or option that I've missed?

3条回答
Root(大扎)
2楼-- · 2020-08-05 11:25

If some of your data already contains HTML, the simplest solution is to use a TemplateColumn rather than a normal column and mark the value as safe:

class Table(tables.Table):
    html_data = tables.TemplateColumn("{{ value|safe }}")
    # ...
查看更多
对你真心纯属浪费
3楼-- · 2020-08-05 11:26

Use mark_safe as follows:

import django_tables2 as tables
from django.utils.safestring import mark_safe

class testTable(tables.Tables):
    id = tables.Column()
    html = tables.Column()

    def render_html(self):
        return mark_safe('some<br/>random<br/>words<br/>returned')

Same question was asked in this thread

查看更多
Root(大扎)
4楼-- · 2020-08-05 11:44

HA. Found it. It wasn't django-tables2 that was auto-escaping my content, it was the django templating system itself: https://code.djangoproject.com/wiki/AutoEscaping.

I had to change my template code to render the django-table2 like this:

{% autoescape off %}
    {% load render_table from django_tables2 %}
    {% render_table route_table %}
{% endautoescape %}
查看更多
登录 后发表回答