94

How can I put comments inside Jinja2 argument list declaration ?

Everything I have tried gives an error: jinja2.exceptions.TemplateSyntaxError: unexpected char u'#'

{{ Switch('var',
    [('1', 'foo'),    #  comment 1
     ('2', 'bar'),    ## comment 2
     ('3', 'rum'),    {# comment 3 #}
     ]) }}


{% macro Switch(var, caselist) %}
    {% for case, action in caselist%}
        CMP  {{var}} {{case}} 
        JNE  {{LABEL}}
        {{action}}
        JMP  {{LABELF}}
{{LABEL}}:  NOP
    {%- endfor %}
{{LABELF}}: NOP
{%- endmacro -%}

In my case Jinja2 is used as macro preprocessor for assembler.

kimstik
  • 1,241
  • 1
  • 13
  • 13

3 Answers3

176

Jinja2 has no support for comments within a {{ ... }} statement. You can only use comments outside of such statements, and then only with {# .. #} or ## comment.

  • {# .. #} is only meant for disabling part of a template or adding comments outside of other Jinja2 syntax. You can't nest these.
  • # statement is the equivalent of {% statement %}, if line statements are enabled and so configured.
  • ## comment only works if line statements are enabled, at which point it regarded as a comment.

Generally, outside of Jinja statements, use comments in the target language instead; e.g. <!-- comment --> when generating XML, etc.

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
  • 2
    external comments looks not such pretty in my case :( – kimstik Nov 26 '12 at 09:56
  • 5
    "`{# .. #}` is only meant for disabling part of a template" – does not match the current documentation, where it is also used as `{# a comment #}`. – timss Mar 07 '16 at 10:24
  • 4
    @timss: That sentence should be read *in the context of this question*, where the OP used `{# comment 3 #}` within a block. Yes, `{# ... #}` are used for commenting, including commenting out (disabling) part of a template. – Martijn Pieters Mar 07 '16 at 11:02
11

Now Jinja2 has a comment statement:

{% comment %}

    <html code/>
    {% some other statements %}
    {{ some.values }}

{% endcomment %}
Dan Netoff
  • 97
  • 1
  • 5
7

I was trying to add comments to Martijn Pieters.

{% .. %} = {# .. #}

{{ .. }} = {# .. #} (same as above)

vallentin
  • 21,302
  • 6
  • 52
  • 73
Paul Thach
  • 91
  • 1
  • 1