[Python] Alternative to "with" template command for loops

Discussão em 'Python' iniciado por Stack, Novembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    I have a template file letter.txt in the format

    Hello {{ first_name }} {{ last_name }}!


    (In reality there are many more variables than these two, but for simplicity I'll stick with only first_name and last_name.)

    This works nicely with a call like

    from jinja2 import Environment, FileSystemLoader
    environment = Environment(loader=FileSystemLoader("./"))

    template = environment.get_template("letter.txt")
    template.render(first_name='Jane', last_name='Doe')


    Now if I have a list of names that should appear, like in a form letter, I need to do the following VERY verbose with statement in the form_letter.txt template file which includes the original untouched letter.txt template.

    {% for person in people %}
    {% with first_name=person.first_name, last_name=person.last_name %}
    {% include 'letter.txt' %}
    {% endwith %}
    ------8<---cut here------------
    {% endfor %}


    and rendering the template via:

    template = environment.get_template("form_letter.txt")
    template.render(people=[{'first_name': 'Jane', 'last_name': 'Doe'},
    {'first_name': 'Bob', 'last_name': 'Builder'},
    {'first_name': 'Sara', 'last_name': 'Sample'}])


    Creating and possibly having to expand the with statement by hand is cumbersome and error prone. Is there a better way to "create a namespace inside a template" automatically from key/value of a dict like object? Like {% with **person %} or something similar?

    Continue reading...

Compartilhe esta Página