Diolor
Diolor

Reputation: 13450

Django all striptags apart from <p>

In the template language is it possible to strip all tags but keeps the ones with the paragraphs(<p>)?

Example:

Given:

<p>In this lesson, you will learn how to apply....</p>
<br>
<img src="http://example.com/photos/b/8/d/0/60312.jpeg" style="max-height : 700px ; max-width : 700px ; margin : 5px">
<p>After attending this workshop you will always be the star!</p>
<ul><li> Test </li></ul>                                  

Final Output:

<p> In this lesson, you will learn how to apply....</p>
<p>After attending this workshop you will always be the star!</p> Test

Upvotes: 1

Views: 215

Answers (2)

Dominic Rodger
Dominic Rodger

Reputation: 99771

You can do this in Python with bleach's clean method, which you could then wrap in a template filter if you need it in your template. Simple usage:

import bleach

text = bleach.clean(text, tags=['p',], strip=True)

Your custom filter would look something like this:

from django import template
from django.template.defaultfilters import stringfilter
import bleach

register = template.Library()

@register.filter
@stringfilter
def bleached(value):
    return bleach.clean(value, tags=['p',], strip=True)

Upvotes: 1

suhailvs
suhailvs

Reputation: 21690

you can do it using templatefilter and beautifulsoup. Install BeautifulSoup. then create a Folder templatetags inside any app folder. you need to add an empty __init__.py inside templatetags folder.

inside the templatetags folder create a file parse.py

from BeautifulSoup import BeautifulSoup
from django import template    
register = template.Library()

@register.filter
def parse_p(html):
    return ''.join(BeautifulSoup(html).find('p')

in template.html

{% load parse %}

{{ myhtmls|parse_p }}

where myhtmls is

<p>In this lesson, you will learn how to apply....</p>
<br>
<img src="http://example.com/photos/b/8/d/0/60312.jpeg" style="max-height : 700px ; max-width : 700px ; margin : 5px">
<p>After attending this workshop you will always be the star!</p>
<ul><li> Test </li></ul>

Upvotes: 1

Related Questions