Created
October 23, 2018 20:54
-
-
Save weedySeaDragon/9566ffc7d4f4aabdb2b09e3748b1475c to your computer and use it in GitHub Desktop.
python, jinja2: Example of namespace and more in a jinja2 template. Written in python so it can be easily run.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# You can use the following in a python console/workspace to see examples of: | |
# - jinja namespace() (reference a variable in the outer scope (loop)) | |
# - passing a value into a template (use a dictionary with each entry = "variable_name": variable_value | |
# - slice() jinja filter (can be used to split a list into columns | |
# | |
# You can also just run this .py file. | |
# | |
# @since 2018-10-23 | |
# @author Ashley Engelund [email protected] < weedySeaDragon @ github > | |
import jinja2 | |
from jinja2 import Template | |
entries = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] | |
templ_content = ("""{% for column in entries | slice(2) %} | |
loop.index: {{ loop.index }} | |
loop.length = {{ loop.length }} | |
{% set colsIndex = namespace(loopindex = loop.index) %} | |
column {{ loop.index }}: | |
{% for entry in column %} | |
loop.index = {{ loop.index }} for entry: {{ entry }} | |
loop.length = {{ loop.length }} | |
outer loop.index = {{ colsIndex.loopindex }} | |
{% endfor %} | |
{% endfor %}""") | |
print(Template(templ_content).render({"entries": entries})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment