So I have this really long URL in my template:
<a href="/route?var1={{ var1 }}&var2={{ var2 }}&var3={{ var3 }}&var4={% for var in var4 %}{{ var }}{% if var != some_value %},{% endif %}{% endfor %}">
thing
</a>
I'm trying to keep my code lines < 120 chars but I can't figure out how to break this string up across multiple lines without adding newlines or breaking the template. How can I do something like this (as I would in python).
<a href="/route?"
"var1={{ var1 }}"
"&var2={{ var2 }}"
"&var3={{ var3 }}"
"&var4={% for var in var4 %}"
"{{ var }}"
"{% if var != some_value %}"
","
"{% endif %}"
"{% endfor %}"
>
thing
</a>
If it weren't for that embedded loop you would do it pretty much exactly how you would do it in Python:
<a href="{{
"/route"
"?var1={}"
"&var2={}"
"&var3={}"
"&var4={}"
"".format(var1, var2, var3, var4)
}}">
thing
</a>
For your embedded loop...
"&var4={% for var in var4 %}"
"{{ var }}"
"{% if var != some_value %}"
","
"{% endif %}"
"{% endfor %}"
...assuming that what you meant is "join together all the elements of var4
that are not equal to the value in some_value
", we can replace it with a reject
filter; take a look at the following example:
import jinja2
t = jinja2.Template(
"""
<a href="{{
"/route"
"?var1={}"
"&var2={}"
"&var3={}"
"&var4={}"
"".format(var1, var2, var3, (var4|reject('eq', some_value)|join(',')))
}}">
thing
</a>
"""
)
print(
t.render(
var1="one",
var2="two",
var3="three",
var4=["this", "is", "a", "test"],
some_value="is",
)
)
Which outputs:
<a href="/route?var1=one&var2=two&var3=three&var4=this,a,test">
thing
</a>