Domanda

Ho provato ad aggiungere un'evidenziazione della sintassi al mio sito Django. Il problema è che sto ottenendo il &nbsp; e <br /> Anche i personaggi formattati. C'è un modo per preservare questi personaggi? Ecco il codice che sto usando:

from BeautifulSoup  import BeautifulSoup
from django import template
from django.template.defaultfilters import stringfilter
import pygments
import pygments.formatters
import pygments.lexers


register = template.Library()

@register.filter
@stringfilter
def pygmentized(html):
    soup = BeautifulSoup(html)
    codeblocks = soup.findAll('code')
    for block in codeblocks:
        if block.has_key('class'):
            try:
                code = ''.join([unicode(item) for item in block.contents])
                lexer = pygments.lexers.get_lexer_by_name(block['class'], stripall=True)
                formatter = pygments.formatters.HtmlFormatter()
                code_hl = pygments.highlight(code, lexer, formatter)
                block.contents = [BeautifulSoup(code_hl)]
                block.name = 'code'
            except:
                raise
    return unicode(soup)
È stato utile?

Soluzione

Bene, Petri ha ragione, il pre -è per i blocchi di codice. Prima di sottolineare che ho appena scritto una funzione per pulire il primo output, è disordinato ma forse qualcuno che ha solo bisogno di rimuovere determinate cose dall'output finale potrebbe trovarlo OK:

from BeautifulSoup  import BeautifulSoup
from django import template
from django.template.defaultfilters import stringfilter
import pygments
import pygments.formatters
import pygments.lexers


register = template.Library()
wanted = {'br': '<br />', 'BR': '<BR />', 'nbsp': '&nbsp;', 'NBSP': '&NBSP;', '/&gt;': ''}

def uglyfilter(html):
    content = BeautifulSoup(html)
    for node in content.findAll('span'):
        data = ''.join(node.findAll(text=True))
        if wanted.has_key(data):
            node.replaceWith(wanted.get(data))
    return unicode(content)     


@register.filter
@stringfilter
def pygmentized(html):
    soup = BeautifulSoup(html)
    codeblocks = soup.findAll('pre')
    for block in codeblocks:
        if block.has_key('class'):
            try:
                code = ''.join([unicode(item) for item in block.contents])
                lexer = pygments.lexers.get_lexer_by_name(block['class'], stripall=True)
                formatter = pygments.formatters.HtmlFormatter()
                code_hl = pygments.highlight(code, lexer, formatter)
                clean = uglyfilter(code_hl)
                block.contents = [BeautifulSoup(clean)]
                block.name = 'pre'
            except:
                raise
    return unicode(soup)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top