If another branch in jinja2

what conditions can we use for branching in jinja2? I mean, can we use expressions like python. For example, I want to check the length of the header. If more than 60 characters, I want to limit it to 60 characters and put "...". Right now, I am doing something similar, but this is not working. error.log reports that the len function is undefined.

template = Template(''' <!DOCTYPE html> <head> <title>search results</title> <link rel="stylesheet" href="static/results.css"> </head> <body> {% for item in items %} {% if len(item[0]) < 60 %} <p><a href="{{ item[1] }}">{{item[0]}}</a></p> {% else %} <p><a href="{{ item[1] }}">{{item[0][40:]}}...</a></p> {% endif %} {% endfor %} </body> </html>''') ## somewhere later in the code... template.render(items=links).encode('utf-8') 
+7
source share
3 answers

You are pretty close, you just need to move it to your Python script. Thus, you can define a predicate as follows:

 def short_caption(someitem): return len(someitem) < 60 

Then register it in the environment by adding it to the "test" dict):

 your_environment.tests["short_caption"] = short_caption 

And you can use it as follows:

 {% if item[0] is short_caption %} {# do something here #} {% endif %} 

For more information, here are jinja docs on user tests

(you only need to do this once, and I think that it is important whether you do this before or after you start creating templates, the documents are unclear)

If you are not already using the environment, you can create it as follows:

 import jinja2 environment = jinja2.Environment() # you can define characteristics here, like telling it to load templates, etc environment.tests["short_caption"] = short_caption 

And then load your template using the get_string () method:

 template = environment.from_string("""your template text here""") template.render(items=links).encode('utf-8') 

Finally, as a side note, if you use a file loader, it allows you to inherit files, import macros, etc. Basically, you just save your file as it is now and tell jinja where the directory is.

+11
source

len is not defined in jinja2, you can use;

 {% if item[0]|length < 60 %} 
+6
source

Jinja2 now has a truncation filter that tests you

truncate(s, length=255, killwords=False, end='...', leeway=None)

Example:

 {{ "foo bar baz qux"|truncate(9) }} -> "foo..." {{ "foo bar baz qux"|truncate(9, True) }} -> "foo ba..." 

Link: http://jinja.pocoo.org/docs/2.9/templates/#truncate

0
source

All Articles