我希望能够在字符串中包含一个自定义的"HTML“标记,例如:"This is a <photo id="4" /> string"
。
在本例中,自定义标记为<photo id="4" />
。我也可以改变这个自定义标签,以不同的方式编写,如果它使它更容易,即[photo id:4]
或其他东西。
我希望能够将这个字符串传递给一个函数,该函数将提取标记<photo id="4" />
,并允许我将其转换为一些更复杂的模板,如<div class="photo"><img src="...." alt="..."></div>
,然后我可以使用它来替换原始字符串中的标记。
我想象它的工作原理是这样的:
>>> content = "This is a <photo id="4" /> string"
# Pass the string to a function that returns all the tags with the given name.
>>> tags = parse_tags('photo', string)
>>> print(tags)
[{'tag': 'photo', 'id': 4, 'raw': '<photo id="4" />'}]
# Now that I know I need to render a photo with ID 4, so I can pass that to some sort of template thing
>>> rendered = render_photo(id=tags[0]['id'])
>>> print(rendered)
<div class="photo"><img src="...." alt="..."></div>
>>> content = content.replace(tags[0]['raw'], rendered)
>>> print(content)
This is a <div class="photo"><img src="...." alt="..."></div> string
我认为这是一个相当常见的模式,比如在博客文章中放一张照片,所以我想知道是否有一个库可以做类似上面示例parse_tags
函数的事情。或者我需要写它吗?
这个照片标签的例子只是一个例子。我希望有不同名称的标签。作为一个不同的例子,也许我有一个人员数据库,我想要一个像<person name="John Doe" />
这样的标记。在这种情况下,我想要的输出类似于{'tag': 'person', 'name': 'John Doe', 'raw': '<person name="John Doe" />'}
。然后,我可以使用这个名字来查找此人,并返回此人的vcard或其他内容的呈现模板。
https://stackoverflow.com/questions/54992490
复制相似问题