Reputation: 871
I have a variable 'text' in python which contains a very long string. And I have a dict whose key is a word/group of words and value is a url. I need to display this variable 'text' using django, creating hyperlink of all the words/group of words from text which are also there in dict. The link is already stored as value in the dict.
text = "taj mahal is in india"
my_dict = { 'taj mahal':'url1', 'india':'url2' }
Display this text using django where 'taj mahal' and 'india' are hyperlinks to url1 and url2 respectively. I tried to use urlize, but it didn't solve the problem.
Upvotes: 2
Views: 2957
Reputation: 473863
You can use replace()
on the text
variable:
>>> text = "taj mahal is in india"
>>> my_dict = { 'taj mahal':'url1', 'india':'url2' }
>>> for key, value in my_dict.iteritems():
... text = text.replace(key, value)
...
>>> text
'url1 is in url2'
or:
>>> text = "taj mahal is in india"
>>> for key, value in my_dict.iteritems():
... text = text.replace(key, '<a href="%s">key</a>' % value)
...
>>> text
'<a href="url1">key</a> is in <a href="url2">key</a>'
If you want then to pass this text
variable to the template, apply safe
filter on it:
{{text|safe}}
Hope that helps.
Upvotes: 4