我一直致力于创建一个python markdown扩展,当使用自定义标记时,该扩展将在我的django项目中插入一个图库。实际的扩展是有效的,但扩展返回的HTML都是编码的。这是我正在使用的扩展程序:
#!/usr/bin/env python
from django.template.loader import render_to_string
from main.models import *
import markdown
version = "0.1.0"
class GalleriaExtension(markdown.Extension):
def __init__(self, configs):
self.config = {
}
# Override defaults with user settings
for key, value in configs:
self.setConfig(key, value)
def add_inline(self, md, name, klass, re):
pattern = klass(re)
pattern.md = md
pattern.ext = self
md.inlinePatterns.add(name, pattern, "<reference")
def extendMarkdown(self, md, md_globals):
self.add_inline(md, 'galleria', Galleria,
r'\[\[(G|g)allery (?P<superpage_id>\w+)\]\]')
class Galleria(markdown.inlinepatterns.Pattern):
def handleMatch(self, m):
try:
images = SuperPage.objects.get(id=m.group('superpage_id')).superpageimage_set.all()
except:
images = None
if images:
rendered = render_to_string('galleria.html', { 'images': images })
else:
rendered = '<b>There are no images for the given ID</b>'
return rendered
def makeExtension(configs=None) :
return GalleriaExtension(configs=configs)
我确保render_to_string
实际上返回了未编码的html。从shell开始,这是输出的一个例子:
render_to_string
的输出:
>>> from django.template.loader import render_to_string
>>> images = SuperPage.objects.get(id=8).superpageimage_set.all()
>>> render_to_string('galleria.html', { 'images': images })
u'<div class=\'galleria_std\'>\n <div class=\'gallery\' >\n <div id=\'stage_gallery\' >\n'
以下是编码的markdown
扩展名的输出:
>>>markdown.markdown('test [[gallery 8]] test', ['galleria'])
u'<p>test <div class=\'galleria_std\'>\n <div class=\'gallery\' >\n'
使用降价扩展程序时,如何使rendered
返回HTML标记而不是编码标记?此外,我将不胜感激任何关于编码的指针(语法,布局等)。我很感激。
答案 0 :(得分:1)
我解决了这个问题:
import markdown
from markdown import Extension
from markdown.inlinepatterns import Pattern
from django.template.loader import render_to_string
from gallery.models import Gallery
class InlineGalleryExtension(Extension):
def extendMarkdown(self, markdownInstance, md_globals):
GALLERY_RE = r'\[\[gallery (?P<id>[0-9]+)\]\]'
inlineGalleryPattern = InlineGallery(GALLERY_RE, markdownInstance)
markdownInstance.inlinePatterns.add('gallery', inlineGalleryPattern, "<not_strong")
class InlineGallery(Pattern):
def handleMatch(self, m):
try:
gallery = Gallery.objects.get(id=m.group('id').strip())
except Gallery.DoesNotExist:
gallery = None
if gallery:
element = render_to_string('gallery/inline_gallery.html', {
'gallery': gallery
})
else:
element = ''
return self.markdown.htmlStash.store(self.unescape(element))
关键解决方案在最后一行。