Search code examples
pythonjinja2prettytable

Is there a way to work with tabulate and jinja2?


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 ?


Solution

  • 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.