0

Suppose you have a word "day" in 100 sentences in your document. You can change the color of that word in the following way:

<span style="color: #ff0000"> day </span>

The problem is that you need to do it 100 times. I am using Django and I want to do it inside template with for loop. So, my problem is now to change the color of a string inside some sentence that I don't know what it will be. I tried with something like:

def colored(sentence, string, color):
    if string not in sentence:
        return sentence
    else:
        colored_string = f'<span style="color: {color}"> {string} </span>'
    return colored_string.join(sentence.split(string))

I thought that that will give me colored variable string, but that wasn't the case. It just returned the string '....<span....' without any including the same stuff. It just like it didn't recognized html at all. What is the correct way of solving the same problem?

Alem
  • 283
  • 1
  • 13
  • Are you saying that the string looks like it should but Django is not letting you render it as HTML? – Mzapp Nov 27 '21 at 19:48
  • It just doesn't work. My idea is to just put that changed colored sentence into template, but the problem is that Django doesn't recognize it like html, but just like sentence string, so it just gives you string with all of those html stuff inside. – Alem Nov 27 '21 at 19:50
  • 1
    I'm pretty sure that that's Django escaping the HTML to prevent XSS attacks. You can try setting the template to allow unsafe HTML if you are sure that the string won't contain malicious code or highlight the words on the frontend using javascript. – Mzapp Nov 27 '21 at 19:55
  • I just solved it with putting in Django template something like {{sentence|safe}} It really works. I just found the answer here https://stackoverflow.com/questions/7786493/convert-string-to-html-code-in-django-template – Alem Nov 27 '21 at 19:58

1 Answers1

0

disable autoescape, django realises that your string is code and just refuses to render it as code for security reasons

ref

Ahmed I. Elsayed
  • 2,013
  • 2
  • 17
  • 30