简体   繁体   English

如何在django模板中将python转换为html

[英]how to convert python to html in django template

I am using json2html to convert json values to html tables in my views.py我在 views.py 中使用 json2html 将 json 值转换为 html 表

render(request, 'home.html', {'value': json2html.convert(json=result)})

where result has json data.其中 result 有 json 条数据。

The above gives me html for json but in home.html template it is not displayed in html table format instead it is displaying like below on the site以上为 json 提供了 html,但在 home.html 模板中,它没有以 html 表格格式显示,而是在网站上显示如下

<ul><li><table border="1"><tr><th>name</th><td>Test</td></tr><tr><th>

my home.html the code looks like this我的 home.html 代码如下所示

<html>
<body>
{{ value }}
</body>
</html>

the variable value has the converted html table code but it is displaying as raw instead it should render as html code.变量值具有转换后的 html 表代码,但它显示为原始代码,而不是应呈现为 html 代码。 How to do this?这该怎么做?

Tell Django that a string is safe and will not be automatically escaped:告诉Django一个字符串是安全的,不会自动转义:

{{ value|safe }}

HTML HTML

<script>
$(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "your home view url",
        success: function (response) {  
            $('body').html(response)
        }
    });
})
</script>

views.py视图.py

return Response('<ul><li><table border="1"><tr><th>name</th><td>Test</td></tr><tr><th>')

upvote and approve if it helps.如果有帮助,请投票并批准。

I found something called format_html under django.utils which does the job.我在 django.utils 下找到了名为 format_html 的东西,它可以完成这项工作。

so the code looks like所以代码看起来像

render(request, 'home.html', {'value': format_html(json2html.convert(json=res))})

Thanks谢谢

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

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