python - 我怎样才能在 jinja2 python 中换行?

标签 python jinja2

如何在 jinja2 中使用 python 进行换行?

下面是我的代码

t1 = Template("{% for i in range(0, a1) %}|{{ mylist1[i] }}{% for j in range(0, (20 - (mylist1[i]|length))) %}{{ space }}{% endfor %}|{{ dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]] }}{% for j in range(0, (20 - (dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]]|length))) %}{{ space }}{% endfor %}|\n{{ string }}{% endfor %}")

此代码将导致: enter image description here 由于它横向太长,我想把它们写成几行。

但是,如果我像下面那样做我通常在 python 中做的事情:

t1 = Template("{% for i in range(0, a1) %}|\
               {{ mylist1[i] }}\
               {% for j in range(0, (20 - (mylist1[i]|length))) %}\
                    {{ space }}\
               {% endfor %}|\
               {{ dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]] }}\
               {% for j in range(0, (20 - (dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]]|length))) %}\
                   {{ space }}\
               {% endfor %}|\n\
               {{ string }}\
               {% endfor %}")

结果是 enter image description here

谁能帮我解决这个问题?

谢谢。

最佳答案

你不应该使用像 in this answer 这样的字符串连接.在您的情况下,利用括号和 implicit string concatenation .

t1 = Template("{% for i in range(0, a1) %}|{{ mylist1[i] }}\n"
              "    {% for j in range(0, (20 - (mylist1[i]|length))) %}\n"
              "        {{ space }}\n"
              "    {% endfor %}|{{ dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]] }}\n"
              "    {% for j in range(0, (20 - (dicts[mylist1[i]][dicts[mylist1[i]].keys()[0]]|length))) %}\n"
              "        {{ space }}\n"
              "    {% endfor %}|\\n{{ string }}\n"  # Notice "\\n" to keep it for Jinja.
              "{% endfor %}")

关于python - 我怎样才能在 jinja2 python 中换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36866128/

相关文章:

python - 数据框:创建新的数据框,在多列的基础上保持重复超过 2 次(时间限制)

python - 为 Jinja2 和 LaTeX 转义斜杠

python - 使用 python/flask 中的 twitter bootstrap css 更改链接的事件类

loops - 使用循环添加到 yaml 列表

python - flask + Jinja : Convert UTC to Local Timezone

python - Pygame 游戏循环语法错误

python - 属性错误: type object 'sklearn.tree._tree.TreeBuilder' has no attribute '__reduce_cython__'

python - 运行 Flask 服务器(Apache)几天时出现 MySQL OperationalError

python - 元组在 CPython 中是如何实现的?

ansible - jinja/ansible 模板中的复杂字符串连接