在 Django 模板中将一些文本替换为粗体

我有一个变量

text = "replace some word"

在一个视图中。我想替换'some'为粗体。像这样:

"replace **some** word"

如何在 Django 模板中处理该变量?


忽然笑
浏览 138回答 2
2回答

慕妹3146593

显然,**不要在模板中使用粗体字符串,您将很难尝试在模板中用适当的开始和结束标记替换这些标记,例如通过自定义过滤器。但是,您可以通过在视图中应用必要的 HTML 并将其标记为安全来将其设为粗体:# views.pyfrom django.utils.safestring import mark_safe# in your view# ...text = "replace some word"# add the appropriate html tagstext = text.replace('some', '<strong>some</strong>')# now you have to mark it as safe so the tags will be rendered as tagstext = mark_safe(text)# ...return render(reqest, template, {.., 'text': text, ...})现在你可以像模板中的普通变量一样使用它 {{ text }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python