简体   繁体   English

如何在 Django 中动态注入 HTML 代码

[英]How to dinamically inject HTML code in Django

In a project of mine I need to create an online encyclopedia.在我的一个项目中,我需要创建一个在线百科全书。 In order to do so, I need to create a page for each entry file, which are all written in Markdown, so I have to covert it to HTML before sending them to the website.为此,我需要为每个入口文件创建一个页面,这些文件都写在 Markdown 中,所以我必须在将它们发送到网站之前将其转换为 HTML。 I didn't want to use external libraries for this so I wrote my own python code that receives a Markdown file and returns a list with all the lines already formatted in HTML.我不想为此使用外部库,所以我编写了自己的 python 代码,该代码接收 Markdown 文件并返回一个列表,其中包含已在 HTML 中格式化的所有行。 The problem now is that I don't know how to inject this code to the template I have in Django, when I pass the list to it they are just printed like normal text.现在的问题是我不知道如何将此代码注入到我在 Django 中的模板中,当我将列表传递给它时,它们就像普通文本一样打印。 I know I could make my function write to an.html file but I don't think it's a great solution thinking about scalability.我知道我可以让我的 function 写入一个 .html 文件,但我不认为这是考虑可扩展性的好解决方案。

Is there a way to dynamically inject HTML in Django?有没有办法在 Django 中动态注入 HTML? Is there a "better" approach to my problem?有没有“更好”的方法来解决我的问题?

You could use the safe filter in your template.您可以在模板中使用安全过滤器。 So it would look like that.所以它看起来像那样。

Assuming you have your html in a string variable called my_html then in your template just write {{ my_html | safe }}假设你的 html 在一个名为 my_html 的字符串变量中,那么在你的模板中只写{{ my_html | safe }} {{ my_html | safe }}

And don't forget to import it!并且不要忘记导入它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM