Django在将字符串推送到模板时添加空格和引号
我试图在视图中构建表并将其推送到该视图的模板,因为在模板中执行该操作并不被证明是可行的。我可以生成一个字符串,其中包含正确的信息,但是如果在浏览器中对该模板变量进行评估,则会出现额外的引号和空格,这些引号和空格似乎不会正确生成表格。Django在将字符串推送到模板时添加空格和引号
这里是从视图代码:
for unique_activity in uniquelist:
currentrow = '<tr data-activityID="' + str(unique_activity[0])+ '">' + '<td>' + str(unique_activity[1]) + '</td>'
for visit in visits_list:
for activity in visit.activity_set.all():
if activity.id == unique_activity[0]:
currentrow = currentrow + '<td>' + 'Reps:'+ str(activity.Repetitions) + '</td>'
else:
noact = True
if noact == True:
currentrow = currentrow + '<td></td>'
currentrow = currentrow + '</tr>\n'
tablerows.append(currentrow)
table = '<table>'
for row in tablerows:
table = table + row
table = table + '</table>'
table = str(table)
输出是什么它需要..一个例子<table><tr data-activityID="1"><td>Initial Evaluation</td><td>Reps:None</td><td></td><td></td></tr> <tr data-activityID="3"><td>Cold Pack</td><td></td><td>Reps:None</td><td></td></tr> <tr data-activityID="6"><td>Recumbent Exercise Bike</td><td>Reps:12</td><td></td><td></td></tr> <tr data-activityID="7"><td>Leg Press</td><td></td><td></td></tr> <tr data-activityID="8"><td>Shoulder Ladder</td><td></td><td></td></tr> </table>
但是,这是在DOM中显示的内容,所有我输出到模板就是{{表}}这就是得到输出到DOM信息,
并导致沮st正在显示的字符串,而不是表格。
这里是模板片断
<body>
{% if activity_list %}
<table>
{% for activity in activity_list %}
<tr>
<td>{{ activity.ActivityType.Name }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
{{ table }}
</body>
我不知道到底是怎么回事......
这听起来像你可能在你的基本模板(或其他地方)有autoescape。如果你希望你的变量被包含为HTML,并且不能安全地转义为文本,那么你必须关闭它的autoescape
,或者用safe template filter来标记它。这里有一个示例模板来尝试和说明。
<p>The following table should be rendered as escaped safe text.</p>
{{ table }}
<p>But with the safe filter, it will be rendered as html!</p>
{{ table|safe }}
<p>And maybe, I want to do this to a few things or have a block of safe html, so I'll just turn the autoescape off for a bit!</p>
{% autoescape off %}
{{ table }}
{{ some_other_safe_html }}
{% endautoescape %}
使用您所提供的代码片段,这里是一个与安全逃生代码:
<body>
{% if activity_list %}
<table>
{% for activity in activity_list %}
<tr>
<td>{{ activity.ActivityType.Name }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
{{ table|safe }}
</body>
贵国是否能显示你的'{{表}}'在模板包含一个片段? – tredzko
完成,感谢您的评论。它是死的香草,虽然...有差异。上面的表。 – Gradatc