Пример использования шаблонизатора Jinja2


Ответы

Вывод значения

from jinja2 import Template

t = Template("Привет {{ username }}!")
t.render(username="RemiZOffAlex")

Вывод значения функции

from jinja2 import Template

t = Template("Привет {{ username(0) }}!")

def getuser(id):
    users = ["RemiZOffAlex"]
    return users[id]

t.render(username=getuser)

Цикл

from jinja2 import Template

t = Template("""{% for user in users -%}
<p>Привет {{ user }}!</p>
{% endfor %}""")
t.render(users=["RemiZOff", "Alex", "RemiZOffAlex"])

Генерация файла виртуального хоста на основе шаблона Apache

templates/apache.vhosts.template

<VirtualHost *:80>
    ServerAdmin info@{{ domain }}
    DocumentRoot "/home/{{ user }}/domains/{{ domain }}"
    ServerName {{ domain }}
    ServerAlias www.{{ domain }}
    ErrorLog "/var/log/httpd/domains/{{ domain }}-error.log"
    CustomLog "/var/log/httpd/domains/{{ domain }}-access.log" common
    AcceptPathInfo On
    <Directory /home/{{ user }}/domains/{{ domain }}>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

templates/nginx.vhosts.template

server {
    listen       80;
    server_name  {{ domain }} www.{{ domain }};
    access_log  /var/log/nginx/domains/{{ domain }}-access.log  main;
    error_log   /var/log/nginx/domains/{{ domain }}-error.log info;
    location / {
        proxy_pass                      http://127.0.0.1:8080/;
        proxy_redirect                  off;
        proxy_set_header                Host            $host;
        proxy_set_header                X-Real-IP       $remote_addr;
        proxy_set_header                X-Forwarded-For $proxy_add_x_forwarded_for;
        client_max_body_size            10m;
        client_body_buffer_size         128k;
        proxy_connect_timeout           90;
        proxy_send_timeout              90;
        proxy_read_timeout              90;
        proxy_buffer_size               4k;
        proxy_buffers                   4 32k;
        proxy_busy_buffers_size         64k;
        proxy_temp_file_write_size      10m;
    }
}

vhosts_generator.py

import os
import sys

from jinja2 import Environment, FileSystemLoader

templatedir = os.path.dirname(os.path.abspath(__file__)) + "/templates"
templates = ['apache.vhosts.template', 'nginx.vhosts.template']

data = [
    {
        'user': 'remizoffalex',
        'domains': [
            'remizoffalex.ru', 'specialistoff.net', 'helpdesk.specialistoff.net, 'pxe.specialistoff.net, 'wiki.specialistoff.net'
        ]
    }
]

for item in data:
    for domain in item['domains']:
        j2_env=Environment(
            loader=FileSystemLoader(templatedir),
            trim_blocks=True)
        for template in templates:
            config=j2_env.get_template(template).render(user=item['user'], domain=domain)
            print('Шаблон: ' + template)
            print(config)

CSS

from jinja2 import Template

data = {
    'font': 'Liberation Sans',
    'font-mono': 'Liberation Mono'
}

template = """
body {
    font-family: '{{ data['font'] }}';
}
code, pre {
    font-family: '{{ data['font-mono'] }}';
}
"""

t = Template(template)
t.render(data=data)