我有一个变量text = "replace some word"在一个视图中。我想替换'some'为粗体。像这样:"replace **some** word"如何在 Django 模板中处理该变量?
2 回答

慕妹3146593
TA贡献1820条经验 获得超9个赞
显然,**不要在模板中使用粗体字符串,您将很难尝试在模板中用适当的开始和结束标记替换这些标记,例如通过自定义过滤器。但是,您可以通过在视图中应用必要的 HTML 并将其标记为安全来将其设为粗体:
# views.py
from django.utils.safestring import mark_safe
# in your view
# ...
text = "replace some word"
# add the appropriate html tags
text = text.replace('some', '<strong>some</strong>')
# now you have to mark it as safe so the tags will be rendered as tags
text = mark_safe(text)
# ...
return render(reqest, template, {.., 'text': text, ...})
现在你可以像模板中的普通变量一样使用它 {{ text }}
添加回答
举报
0/150
提交
取消