Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if else branching in jinja2

what sort of conditions can we use for branching in jinja2? I mean can we use python like statements. For example, I want to check the length of the caption. If bigger than 60 characters, I want to limit it to 60 characters and put "..." Right now, I'm doing something like this but it doesn't work. error.log reports that 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')
like image 441
shashydhar Avatar asked Jun 30 '12 05:06

shashydhar


1 Answers

You're pretty close, you just have to move it to your Python script instead. So you can define a predicate like this:

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

Then register it on the environment by adding it to the 'tests' dict ):

your_environment.tests["short_caption"] = short_caption

And you can use it like this:

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

For more info, here's the jinja docs on custom tests

(you only have to do this once, and I think it matters whether you do it before or after you start rendering templates, the docs are unclear)

If you aren't using an environment yet, you can instantiate it like this:

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 through 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 the file loader, it lets you do file inheritance, import macros, etc. Basically, you'd just save your file as you have it now and tell jinja where the directory is.

like image 118
Jeff Tratner Avatar answered Oct 03 '22 03:10

Jeff Tratner