【问题标题】:Django - String customizing color for templateDjango - 为模板自定义颜色的字符串
【发布时间】:2019-05-16 03:53:32
【问题描述】:

嘿,是否可以在我的视图中自定义我在模板上输出的文本,其中某些单词使用不同的颜色?例如,我有一个词输出到我的模板:

def test(request):
    text = 'test text but this section is red'
    return render(request, 'test.html', {'text':test}

如何为“此部分为红色”获得不同的颜色,但其余部分正常显示在我的模板中?

【问题讨论】:

    标签: python html django django-templates django-views


    【解决方案1】:

    将其分成两部分,以便在模板中区分它们。

    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>
    

    【讨论】:

    • 文本长度可变,不知道要多长怎么办?
    • @Noobfor 如果是这样的话,我会让创建内容的人能够使用适当的文本编辑器按照他们想要的方式设置样式,然后您就不用担心了。
    【解决方案2】:

    是的,您可以通过不同的方法实现这一点。

    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'}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-15
      • 2011-08-27
      • 1970-01-01
      • 2015-11-09
      • 1970-01-01
      • 2015-03-02
      • 2019-04-03
      • 1970-01-01
      相关资源
      最近更新 更多