Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
How to use if in jinja2 template engine?

Jinja2 is a modern and designer-friendly templating language for Python, modelled after Django’s templates. It is fast, widely used and secure.

If you want to use conditional statements like if inside of template engine you should use a syntax like below:
{% if status == 'success' %}
Some text for successful procedure
{% else %}
Some text for not successful procedure
{% endif %}

#python #jinja2 #template_engine #template
To set a variable in jinja2 you can use set as below:
{% set pages_title = 'Pages' %}

As you notice we have used {% %} to set a variable not { }.

#variable #define #jinja2 #template
More about jinja2:

If you want to set a variable named button:
{% set button = 'Login' %}

If you want to include a partial template (child template) into your parent template use include:
{% include 'fa.button.tpl' %}

BE CAREFUL that we have used {% NOT {{ for the code block.

If one of your templates inherits from a main layout use extends directive:
{% extends "layout.tpl" %}

#python #jinja2 #extends #include #set #variable #set_variable #layout
If you want to comment a block of code out in Jinja2 template, use {# ... #}. It can also span into multiple lines:
{#
<tr class="">
<td colspan="2" style="font-family:Ubuntu,Helvetica,Arial,sans-serif; padding: 0px 0px 0px 20px;" class="">
Regards,
</td>
</tr>
<tr class="">
<td colspan="2" style="font-family:Ubuntu,Helvetica,Arial,sans-serif; padding: 0px 0px 30px 20px;" class="">
SYSTEM INFO
</td>
</tr>
#}

#python #jinja2 #comment #comment_out
jinja2 has tons of filters for strings, lists, etc that can be used to make the process of, um well, filtering simpler.

To apply a filter you can use pipe symbol (|). In order to lower case`/`upper case a string:
{{"SOMETHING"|lower}}
{{"sOmThing"|upper}}

Or let's say getting the max number from a list:
{{ [1, 2, 3]|max }}

The filters are endless, see below for more:
http://jinja.pocoo.org/docs/2.10/templates/#filters

#python #jinja2 #template #filter #uppercase #lowercase #max
How to use thousand separator in Python & Jinja2?

The python way is to use format as below:

'user credit is {:,}'.format(10000)


And in Jinja2 it is like the following line:

user credit is {{ '{0:,}'.format(user_credit | int) }}


#python #jinja2 #separator #thousand_separator
As you may know you can use capitalize to make the first letter of a word upper case. For example you can turn failed to Failed.

In Jinja2 you can use title to do the same job:

{{ "failed" | title }}

#python #jinja2 #filter #title #capitalize