Jinja2 inline comments

PythonMacrosJinja2Comments

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

Now Jinja2 has a comment statement:

{% comment %}

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

{% endcomment %}

Solution 3 - Python

I was trying to add comments to Martijn Pieters.

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkimstikView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonDan NetoffView Answer on Stackoverflow
Solution 3 - PythonPaul ThachView Answer on Stackoverflow