Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja has a "center" formatting option, but how about "right align"?

Tags:

python

jinja2

Say I have

{% for key,value in adict %}
{{key}}:{{value}}
{% endfor %}

How do I ensure that all of the keys are padded such that the output is

     something: 1
someotherthing: 3
  thelastthing: 2

edit: This is not a webpage I am working on, I am just getting string output for printing.

like image 595
RodericDay Avatar asked Jul 01 '13 12:07

RodericDay


People also ask

How does Jinja templating work?

It is a text-based template language and thus can be used to generate any markup as well as source code. The Jinja template engine allows customization of tags, filters, tests, and globals. Also, unlike the Django template engine, Jinja allows the template designer to call functions with arguments on objects.

Can we use Jinja template in JavaScript?

Jinja is one of the most used template engines for Python. This project is a JavaScript implementation with emphasis on simplicity and performance, compiling templates into readable JavaScript that minifies well.

What is context in Jinja2?

Context contains the dynamic content that you want to inject in your template when it is being rendered.

What is Jinja in HTML?

Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.


2 Answers

{{ key.rjust(20) }}:{{value}} did the trick

I did not know you could just call python string commands from the box. If someone has a more "jinja" solution, using pipes, I will give the answer to that.

like image 192
RodericDay Avatar answered Nov 07 '22 00:11

RodericDay


Use the build-in Jinja2 filter called format. For example:

Left aligned string of width 20:

{{ "%-20s"|format(variable) }} 

Right aligned string of width 20:

{{ "%20s"|format(variable) }}

Your case:

{{ "%20s:%s"|format(key, value) }}
like image 27
Rick van der Zwet Avatar answered Nov 07 '22 02:11

Rick van der Zwet