Skip to content
Advertisement

Is it possible to store some HTML code in “context” and then make it work on one of the templates?

My goal is to get this table’s code from another website using selenium, store it in the context dictionary to then place it in one of the templates in a way that it won’t show the code as text but it will make it part of the page’s code itself.

tab = driver.find_element_by_class_name("table-responsive")
tab = tab.get_attribute("outerHTML")

context = {'tab': tab,
          }

This way I already managed to store the code in the context dictionary and then I used the Django built-in function to pass the context keys to templates {{ tab }}. I’m trying to understand if it’s possible to make it work as proper HTML code in a template even if it’s just a key in a dictionary.

Advertisement

Answer

Yes, you can do that. By default, every variable is escaped when you insert it into the template. That’s done to prevent XSS attacks: if the is a malicious executable code in the variable content, it can run at the user’s browser and act on their behalf.

However, if you are certain about this content, you can mark it as safe to prevent escaping.

{{ tab|safe }}
Advertisement