Search code examples
djangodjango-templatesdjango-template-filters

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" />

Solution

  • 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.