Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django template filter remove html tags

In the following django template variable .Is it possible to remove the html tags via django template filters

 {{myvar|safe}}

The following would output an html like

     <div>sddfdsfsdfsdf sd fsdf sd fsdf </div><a>This link</a><img src="some source" />
like image 577
Rajeev Avatar asked Jul 07 '11 06:07

Rajeev


3 Answers

Have you looked at striptags? It would turn your HTML into this (minus the syntax highlighting of This, of course):

sddfdsfsdfsdf sd fsdf sd fsdf This link

But be aware that this template filter uses a regex to strip out the HTML tags. As we know, regexes are not the right tool for working with HTML most of the time. If your HTML comes from the outside, make sure to sanitize it with a real HTML parser, e.g. lxml.html.clean.

like image 129
Benjamin Wohlwend Avatar answered Oct 20 '22 09:10

Benjamin Wohlwend


striptags

Makes all possible efforts to strip all [X]HTML tags.

For example:

{{ myvar|striptags }}

If myvar is <b>Joel</b> <button>is</button> a <span>slug</span>, the output will be Joel is a slug.

You can also use strip_tags in your python code i.e. in a form.

For example, in a Form clean method:

class AddressForm(forms.ModelForm):

    class Meta:
        model = Address

    def clean(self):
        from django.utils.html import strip_tags
        cleaned_data = super(AddressForm, self).clean()
        cleaned_data['first_name'] = strip_tags(cleaned_data.get('first_name'))
        return cleaned_data

See Django HTML Utils, Also check out this simple Django HTML Sanitizer App.

like image 31
jatinkumar patel Avatar answered Oct 20 '22 07:10

jatinkumar patel


To strip/remove HTML tags from an existing string we can use the strip_tags function.

import the strip_tags

from django.utils.html import strip_tags

simple string with html inside.

html = '<p>paragraph</p>'

print html # will produce: <p>paragraph</p>
 

stripped = strip_tags(html)
print stripped # will produce: paragraph

This is also available as a template tag:

{{ somevalue|striptags }}

If you want to remove only specific tags you need to use the removetags

from django.template.defaultfilters import removetags
html = '<strong>Bold...</strong><p>paragraph....</p>'
stripped = removetags(html, 'strong') # removes the strong only.
stripped2 = removetags(html, 'strong p') # removes the strong AND p tags.
 

Also available in template:

{{ value|removetags:"a span"|safe }}
like image 1
motad333 Avatar answered Oct 20 '22 07:10

motad333