最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jinja2 - Is there a way to manually trim whitespace? - Stack Overflow

programmeradmin1浏览0评论

I would like to do something like this in jinja2:

   {{ lengthy_snap_expression }}, {% trim -%}
   {{ lengthy_crackle_expression }}, {% trim -%}
   {{ lengthy_pop_expression }}

to produce

   SNAP, CRACKLE, POP

where SNAP, CRACKLE, and POP are the results of evaluating lengthy_snap_expression, lengthy_crackle_expression and lengthy_pop_expression, all of which are lengthy expressions in my case

My intent is to keep the template readable but remove space from the generated output.

Otherwise it seems like I have to write on one line

{{ lengthy_snap_expression }}, {{ lengthy_crackle_expression }}, {{ lengthy_pop_expression }}

and in my case this can be several hundred characters which would be better split for readability in the template itself.

Any suggestions?

I would like to do something like this in jinja2:

   {{ lengthy_snap_expression }}, {% trim -%}
   {{ lengthy_crackle_expression }}, {% trim -%}
   {{ lengthy_pop_expression }}

to produce

   SNAP, CRACKLE, POP

where SNAP, CRACKLE, and POP are the results of evaluating lengthy_snap_expression, lengthy_crackle_expression and lengthy_pop_expression, all of which are lengthy expressions in my case

My intent is to keep the template readable but remove space from the generated output.

Otherwise it seems like I have to write on one line

{{ lengthy_snap_expression }}, {{ lengthy_crackle_expression }}, {{ lengthy_pop_expression }}

and in my case this can be several hundred characters which would be better split for readability in the template itself.

Any suggestions?

Share Improve this question edited Mar 17 at 7:48 DarkBee 15.5k8 gold badges72 silver badges118 bronze badges asked Mar 14 at 17:42 Jason SJason S 190k175 gold badges632 silver badges1k bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

Comments seem to do the trick, although somewhat unsatisfyingly so.

   {{ lengthy_snap_expression }}, {#
 #}{{ lengthy_crackle_expression }}, {#
 #}{{ lengthy_pop_expression }}

Dashes can be used to specify manual whitespace trimming in {{ ... }} and {# ... #} just like they do in {% ... %}, so if you render:

{{ 'SNAP' }},
{{- 'CRACKLE' }},
{{- 'POP' }}

you'd get:

SNAP,CRACKLE,POP

and if you want to preserve the whitespace after each comma you can use a dash at the end of an empty comment following a whitespace after each comma:

{{ 'SNAP' }}, {# -#}
{{ 'CRACKLE' }}, {# -#}
{{ 'POP' }}

which outputs:

SNAP, CRACKLE, POP
发布评论

评论列表(0)

  1. 暂无评论