簡體   English   中英

Django-模板的字符串自定義顏色

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM