有没有办法使用tabulate和jinja2一起工作?

huangapple go评论76阅读模式
英文:

Is there a way to work with tabulate and jinja2?

问题

我遇到了一个问题,我使用PrettyTable来生成表格,表格的内容来自一个JSON文件Json文件。在终端中,我可以得到正确的布局在终端中打印,但当我将它放在一个Jinja文件中时,间距混乱了使用PIL生成图像的Jinja输出

这是创建表格的代码表格代码,这是Jinja2部分的代码Jinja代码

我尝试过更改Prettytable的列宽参数,但没有成功。我需要在我使用的字符串上使用len(),然后减少或添加空格以产生正确的输出吗?

英文:

I have this issue where I use PrettyTable to generate tables with content coming from a json fileJson file I get the correct layout in terminalPrinting in terminal but when i put it inside a jinja file the spacing are messed upOutput of jinja using PIL to obtain an image

Here's the code for creating the tableCode for table
And here's the jinja2 part Jinja code

I tried to change the parameters of Prettytable for column width but without success.
Do I need to use len() on the string that I use and then reduce or add space to produce a correct ouput ?

答案1

得分: 0

你的目标是在Jinja中显示对齐的表格。

你可以在你的脚本中使用len()函数来操作字符串,但我认为更好的方式是在Jinja中生成正确的间距,将视图代码与脚本代码分开。

我认为在Jinja中创建漂亮的表格的正确方式是使用CSS代码。

你可以将表格保存为HTML元素到文件中,例如:

html_table = x.get_html_string()
cwd = Path.cwd()
with Path(f"{cwd}/templates/my_table.html").open(mode="w", encoding="utf-8") as fp:
    fp.write(html_table)

然后,你可以在任何模板中渲染它,并在Jinja模板中包含此表格,方法如下:

{% include 'my_table.html' %}

这将显示表格,并且你可以按照你的喜好对其进行样式化。

英文:

your goal is to display aligned table in jinja

You can use len() on the string in your script but i think it is better to generate correct spacing in jinja. You separate view code from your script code.

I think the correct way to create a beautiful table in jinja is by using css code.

You can save your table as html elements to a file, for instance:

html_table = x.get_html_string()


# from pathlib import Path
# `cwd`: use current directory
    cwd = Path.cwd()

    with Path(f"{cwd}/templates/my_table.html").open(mode="w", encoding="utf-8") as fp:
        fp.write(html_table)

then you can render it to any template and include this table in a Jinja template by using :

{% include 'my_table.html' %}

This will display the table and you can style it however you like.

huangapple
  • 本文由 发表于 2023年5月11日 16:43:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76225720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定