如何在Django模板中添加注释?

278

我想在这里添加一行注释:

{% if something.property %}
    <table>
        <tr>...



{% # this is a comment %}
{% if something.property %}
    <table>
        <tr>...
6个回答

425

如Miles所回答的那样,{% comment %}...{% endcomment %}用于多行注释,但您也可以像这样在同一行上注释文本:

{# some text #}

20
如果你有一个 {% extends "file.html" %} 标签,你应该将它放在模板文件的最顶部,甚至在 {% comment %}...{% endcomment %} 之前,否则你会得到一个 <ExtendsNode: extends "file.html"> must be the first tag in the template 错误。我是在提醒那些想要把多行注释放在模板顶部的人。 - pebox11

169

32

使用{# #}表达式,如下所示:

{# Everything you see here is a comment. It won't show up in the HTML output. #}

9

如果你想要对 Django 模板格式代码进行评论,这种方式可能会有所帮助。

{#% include 'file.html' %#} (正确的方式)

即使使用 HTML 注释对以下代码进行注释,它仍然会执行。

<!-- {% include 'file.html' %} --> (错误的方式)


5

这是单行注释

{# <p>This is comment</p> #}

这是 多行注释
{% comment "This is an optional note for comments" %}
    <p>This is comment</p>
    <p>This is comment</p>
    <p>This is comment</p>
{% endcomment %}

0

如果你想在{% extends ... %}之前添加注释,那么这种方法行不通。在这种情况下,最好使用

<!--
# comment 1
# comment 2
# comment 3
-->

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接