Python Bottle 服务器模板返回格式错误的 html 代码

Python Bottle server template returning ill formatted html code

所以在接下来的 bottle 服务器路由期间一切正常...

@route('/IFC/config/<policy>')
def config(policy):
    if policy == "test":
        html_nodes = ""
        Nodes = IFC_main.get_nodes(ipaddr,username,password)
        for node in Nodes:
            html_nodes += '<li>'+node["name"]+'</li>'
        return template("mgmt.tpl",html_nodes = html_nodes)

除了当我查看生成的网页的源代码时,它应该是一个包含我提供的值的下拉菜单,但我却得到了这个...

<script language="JavaScript" type="text/javascript" src="/static/mgmt.js">               </script>
<link rel="stylesheet" type="text/css" href="/static/mgmt.css">

<body style = "background-color:#CCCCCA">
<img id="banner" style = "bg-color:CBCCCE" src="static/Cisco_emailHeader.png" alt="Banner Image"/>
<div style="width: 800px;height: 100px;position: absolute;top:0;bottom: 0;left: 0;right: 0;margin: auto;">
<h1>Management Connectivity</h1>
 <ul class="dropdown-menu">
 &lt;li&gt;calo2-leaf3&lt;/li&gt;&lt;li&gt;calo2- spine1&lt;/li&gt;&lt;li&gt;calo2-leaf2&lt;/li&gt;&lt;li&gt;calo2- leaf1&lt;/li&gt;&lt;li&gt;apic2&lt;/li&gt;&lt;li&gt;calo2- spine2&lt;/li&gt;&lt;li&gt;apic1&lt;/li&gt;&lt;li&gt;apic3&lt;/li&gt;
</ul>
</div>
</body>

我知道我需要将我传递的字符串转换为模板,但我一直无法弄清楚是什么。我假设其他人对这个问题有 运行。

您需要将循环移动到模板文件中,

% for node in nodes:
    <li>{{ node.name }}</li>
% end

代码将更改为,

@route('/IFC/config/<policy>')
def config(policy):
    if policy == "test":
        nodes = IFC_main.get_nodes(ipaddr,username,password)
        return template("mgmt.tpl", nodes=nodes)

您可以用感叹号开始语句以禁用该语句的转义:

>>> template('Hello {{name}}!', name='<b>World</b>')
u'Hello &lt;b&gt;World&lt;/b&gt;!'
>>> template('Hello {{!name}}!', name='<b>World</b>')
u'Hello <b>World</b>!'