Reputation: 13056
I have a Jinja 2 template like this:
foo{# comment #}
bar
When trim_blocks
is enabled, the template renders as:
foobar
I want the template to render like this:
foo
bar
I tried using the +#}
syntax to disable trimming after the comment but it didn't work. How can I do this? I don't want to have to add an extra line break after every single comment in my template.
Edit: I am not in control of the code that renders the template, so any solution must be within the template itself.
Upvotes: 2
Views: 1324
Reputation: 160033
Simply output a newline using {{ "\n" }}
after the comment:
foo{# comment about foo #}{{ "\n" }}
bar
Ideally you could change the rendering code to not strip comments, but if you can't this will preserve the desired output.
Upvotes: 4
Reputation: 15120
You can change lexing rules for comment blocks
import re
from jinja2 import Environment
from jinja2.lexer import TOKEN_COMMENT, TOKEN_COMMENT_BEGIN, TOKEN_COMMENT_END, Failure
env = Environment()
env.trim_blocks = True
c = lambda x: re.compile(x, re.M | re.S)
e = re.escape
comment_block_suffix_re = ''
env.lexer.rules[TOKEN_COMMENT_BEGIN] = [
(c(r'(.*?)((?:\-%s\s*|%s)%s)' % (
e(env.comment_end_string),
e(env.comment_end_string),
comment_block_suffix_re
)), (TOKEN_COMMENT, TOKEN_COMMENT_END), '#pop'),
(c('(.)'), (Failure('Missing end of comment tag'),), None)
]
See source code of lexer module for details
Upvotes: 1