如何在Django模板中添加注释

Ale*_* S. 193 django django-templates

我想用一句话来评论这个

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



{% # this is a comment %}
{% if something.property %}
    <table>
        <tr>...
Run Code Online (Sandbox Code Playgroud)

Van*_*ale 287

作为Miles的答案,{% comment %}...{% endcomment %}用于多行注释,但您也可以在同一行注释掉文本,如下所示:

{# some text #}
Run Code Online (Sandbox Code Playgroud)

  • 是的,但是如果你有一个`{%extends"file.html"%}"标签你应该把它放在模板文件的最顶层,甚至在`{%comment%}`之后......`{%endcomment% }`,否则你会得到一个`<ExtendsNode:extends"file.html">必须是模板中第一个标记错误.我想说如果有人想将多行注释放在模板的顶部. (10认同)

mip*_*adi 25

使用{# #}符号,如下所示:

{# Everything you see here is a comment. It won't show up in the HTML output. #}
Run Code Online (Sandbox Code Playgroud)


Rah*_*and 9

如果您想注释一些 Django 模板格式代码,这种方法会很有帮助。

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

如果使用 HTML Comment 进行注释,以下代码仍会执行。

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


Has*_*tax 8

与传统的html注释相反:

<!-- not so secret secrets -->
Run Code Online (Sandbox Code Playgroud)

Django模板注释未在最终html中呈现。因此,您可以随意在其中填充实现细节,如下所示:

多行:

{% comment %}
    The other half of the flexbox is defined 
    in a different file `sidebar.html`
    as <div id="sidebar-main">.
{% endcomment %}
Run Code Online (Sandbox Code Playgroud)

单线:

{# jquery latest #}

{#
    beware, this won't be commented out... 
    actually renders as regular body text on the page
#}
Run Code Online (Sandbox Code Playgroud)

我发现这对于<a href="{% url 'view_name' %}"尚未创建的视图特别有用。


小智 6

这是单行注释

{# <p>This is comment</p> #}
Run Code Online (Sandbox Code Playgroud)

这是多行注释

{% comment "This is an optional note for comments" %}
    <p>This is comment</p>
    <p>This is comment</p>
    <p>This is comment</p>
{% endcomment %}
Run Code Online (Sandbox Code Playgroud)