Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress python markdown wrapping text in <p></p>

I'm using python markdown as a filter for Jinja2 to generate html. As part of that, I fill in table entries from the render input. Passing the input through the markdown filter always wraps the text in paragraph tags, and thus every entry in the table is wrapped in <p></p>, which I don't want.

I've read through the markdown docs and the 3rd party extension lists, but it appears there's no way to suppress this behavior other than writing my own extension. Is there no other way to suppress the paragraph tag wrapping? Or am I going about this the wrong way?

Update: Here's the filthy dirty awful hack I'm using for now:

def safe_markdown(text):
  p = '<p>'
  np = '</p>'
  md = markdown.markdown(text)
  if md.startswith(p) and md.endswith(np): #you filthy bastard
    md = md[len(p):-len(np)]
  return jinja2.Markup(md)

env = jinja2.Environment(...)
env.filters['markdown'] = safe_markdown 

Update 2 (Response to Aaron's answer):

Appreciate the help, but it's definitely the markdown causing the problem. Here's an example portion of the jinja template:

        {%- if spc.docs -%}
<td>{{ spc.docs|markdown }}</td></tr>
        {%- else -%}
<td></td></tr>
        {%- endif -%}

If spc.docs is simply 'foo' the generated html will wind up as <td><p>foo</p></td></tr> unless I use the filthy hack.

Update 3

Here's a less nasty hack, although still a hack and not really an 'answer', IMO.

def safe_markdown(text):
    md = markdown.markdown(text)
    return jinja2.Markup(md)

def safe_markdown_td(text):
    text = ''.join(['<td>', text, '</td>'])
    return safe_markdown(text)

env = jinja2.Environment(...)
env.filters['markdown'] = safe_markdown
env.filters['markdowntd'] = safe_markdown_td

Then the template becomes:

        {%- if spc.docs -%}
{{ spc.docs|markdowntd }}</tr>
        {%- else -%}
<td></td></tr>
        {%- endif -%}
like image 356
elhefe Avatar asked Feb 13 '26 07:02

elhefe


2 Answers

Any time you use markdown, you have to accept some pretty severe compromises on the final structure of the html. There are a host of structures you simply cannot express. Don't think of it as a substitute for html, think of it as another language to simply write content.

What might be happening is that wrapping your table cell contents in paragraph tags is messing up your layout, in which case you should fix that with CSS:

td p {
  margin: 0;
  padding: 0;
}
like image 107
Christian Oudard Avatar answered Feb 15 '26 21:02

Christian Oudard


... yet another way to remove the irritating outer tags is to write a simple stripping function:

def strip(s):
    """ strips outer html tags """

    start = s.find('>')+1
    end = len(s)-s[::-1].find('<')-1

    return s[start:end]
like image 45
Jev Avatar answered Feb 15 '26 21:02

Jev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!