我想编写一个过滤器来替换我的流场文本中的一些 $variables$。在我的“页面”模型中执行此操作的最佳方法是什么?我尝试了以下方法,但如果我将模型保存为草稿并在之后发布,它有时会不起作用。有谁知道这样做的更好方法?
class CityPage(Page, CityVariables):
cityobject = models.ForeignKey(CityTranslated, on_delete=models.SET_NULL, null=True, blank=True)
streamfield = StreamField(BasicStreamBlock, null=True, blank=True)
content_panels = Page.content_panels + [
FieldPanel('cityobject', classname="full"),
StreamFieldPanel('streamfield'),
]
def get_streamfield(self):
for block in self.streamfield:
if type(block.value) == unicode:
block.value = self.replace_veriables(block.value)
elif type(block.value) == RichText:
block.value.source = self.replace_veriables(block.value.source)
else:
print "notimplemented"
return self.streamfield
这只是用我的数据库中的值替换 $variables$ 的类。
class CityVariables():
def replace_veriables(self, repstr):
reprules = self.get_city_context()
for key, value in reprules.iteritems():
repstr = repstr.replace(key, value)
return repstr
def get_city_context(self):
context = {}
if self.cityobject.population:
context['$population$'] = unicode(self.cityobject.population)
if self.cityobject.transregion:
context['$region$'] = unicode(self.cityobject.transregion)
return context
class BasicStreamBlock(blocks.StreamBlock):
h2 = blocks.CharBlock(icon="title", classname="title")
h3 = blocks.CharBlock(icon="title", classname="title")
h4 = blocks.CharBlock(icon="title", classname="title")
h5 = blocks.CharBlock(icon="title", classname="title")
paragraph = blocks.RichTextBlock(icon="pilcrow")
image = ImageChooserBlock(label="Image", icon="image")
aligned_html = blocks.RawHTMLBlock(icon="code", label='Raw HTML')