[英]Django - String customizing color for template
嘿,是否可以在我的视图中自定义在模板上输出的带有特定颜色的某些单词的文本? 例如,我有一个单词输出到模板中:
def test(request):
text = 'test text but this section is red'
return render(request, 'test.html', {'text':test}
如何为“此部分为红色”获得其他颜色,但其余部分正常显示在模板中?
将其拆分为两个,以便可以在模板中区分它们。
def test(request):
text = 'test text but'
red_text = 'this section is red'
return render(
request,
'test.html',
{'text': text, 'red_text': red_text}
)
然后在模板中;
<p>{{ text }} <span style="color: red">{{ red_text }}</span></p>
是的,您可以使用不同的方法来实现。
Django在模板中具有safe
过滤器和自动autoescape
标记。
def test(request):
text = '<span style="color: red">test text but this section is red</span>'
return render(request, 'test.html', {'text':test}
并在模板中使用
{{ text|safe }}
要么
{% autoescape off %} {{ text }} {% endautoescape %}
或者您可以使用mark_safe
编写自己的自定义过滤器
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def custom_filter(text, color):
safe_text = '<span style="color:{color}">{text}</span>'.format(color=color, text=text)
return mark_safe(safe_text)
并在模板中;
{{ text|custom_filter:'red'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.