从视图发送HTML到Django模板 [英] sending html to django template from view

查看:30
本文介绍了从视图发送HTML到Django模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是django的新手,所以我可能会以错误的方式来做这件事(肯定是我).

I am new to django so I may be going about this the wrong way (pretty sure I am).

尝试获取一个网页,以在显示服务器列表状态的表中显示来自PostgreSQL数据库的数据.

Trying to get a webpage to display data from a postgresql DB in a table showing a status for a list of servers.

这是模板的一部分

<div class"row"=""><div class="span3" style="background-color:lightyellow; margin-left:20px">
<table class="table table-bordered table-condensed">
        <thead>
          <tr>
            <th>Server</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
        {{ res }}
        </tbody>
      </table>
</div></div>

在我看来,我有这个

message = []
for res in data:
    message.append("          <tr>")
    message.append("            <td>" + str(res).split("'")[1] + "</td>")
    if str(res).split("'")[3] == 'No':
        message.append("            <td><FONT COLOR=\"008200\">Available</FONT> </td>")
    else:
        message.append("            <td><FONT COLOR=\"FF0000\">Down</FONT> </td>")
    message.append("          </tr>")

return render_to_response('health.html', {'res':message}, context_instance=RequestContext(request))

如果我打印出来而不是执行追加操作,则会得到期望的结果HTML.

If I print that instead of doing the append I get the resulting HTML I would expect.

目前,该表格的网页上没有显示任何内容.

As it currently is, I don't get anything displayed on the webpage in that table.

我不希望它呈现列表,但即使格式不正确,也会认为表中应该出现了一些东西.

I don't expect it to render the list necessarily, but would have thought something should have showed up in the table even if it was incorrect format.

是否应在模板而不是视图中完成HTML处理?

Should this HTML processing be done in the template and not the view?

推荐答案

是的,通常最好在模板中进行所有HTML处理.这样,您可以将数据库访问逻辑与显示逻辑分开,从而减少耦合.这也意味着您可以轻松地重新使用模板.

Yes, it is usually best to do all HTML processing in the template. This way you can separate your database access logic from your display logic and thereby reduce coupling. It also means you can easily re use template.

因此,您应该使用view函数来获取适当的对象,并将它们作为变量传递给模板.

So you should use the view function to get the appropriate objects and pass them to the template as variables.

仍然,您处于正确的轨道上.为了使您的{{res}}变量正确显示,我认为您需要将模板更改为.

Still, you are sort of on the right track. In order for your {{res}} variable to display properly I think you will need to change the template to.

<tbody>
    {% for message in res %}
    {{ message }}
    {% endfor %}
</tbody>

这应该遍历传递给模板的 res 变量中的元素.

This should iterate over the elements in the res variable which you passed to the template.

这篇关于从视图发送HTML到Django模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆