Home > Net >  how to color text with condition in django?
how to color text with condition in django?

Time:11-30

I have a django app and I want to color some text, if that text is true in dictionary.

So I have this method:views.py

def data_compare2(request):

    template = get_template("main/data_compare.html")
    dict2 = {"appel": 3962.00, "waspeen": 3304.07, "ananas":24}
    context = {"dict2": dict2}
    res = dict((v,k) for k,v in dict2.items())
    
    return HttpResponse(template.render(context, request, res[3962.00]))

and this is the template:

<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>

    <body>

        <div >


            {% for key, value in dict1.items %}
            {%if {{res}} %}
            <div style="background-color:'red'"></div>
            {%endif%}
            {{ key }} {{value}}<br>
            {% endfor %}

        </div>

    </body>

</html>

So the text appel": 3962.00 has to appear in red.

Question: how to make the founded text in dictionary red?

CodePudding user response:

I would separate fruits from the condition, inside the context. Transform the condition into a list to check on the template.

views.py

def data_compare2(request):
    fruits = {"appel": 3962.00, "waspeen": 3304.07, "ananas":24,}
    condition = ['appel', 'ananas']

    context = {
        'fruits': fruits,
        'condition': condition
    }
    
    return render(request, 'main/data_compare.html', context)

template.html

{% extends 'base.html' %}

{% block content %}
    <div >
        {% for key, value in fruits.items %}
            <span {% if key in condition %} style="color: red;" {% endif %}>{{ key }}: {{value}}</span><br>
        {% endfor %}
    </div>
{% endblock %}

This will result in 'appel' and 'ananas' being red.

  • Related