casting ints to str in Jinja2

Question:

I want to cast an int that’s passed to the template through the url, but it says that the str function isn’t defined.

How do I get around this?

Here’s my code:

{% extends "base.html" %}

{% block content %}

    {% for post in posts %}
    {% set year = post.date.year %}
    {% set month = post.date.month %}
    {% set day = post.date.day %}
    {% set p = str(year) + '/' + str(month) + '/' + str(day) + '/' + post.slug %}
    <h3>
        <a href="{{ url_for('get_post', ID=p) }}">
            {{ post.title }}
        </a>
    </h3>

        <p>{{ post.content }}</p>
    {% else: %}
            There's nothing here, move along.
    {% endfor %}

{% endblock %}
Asked By: Mahmoud Hanafy

||

Answers:

You may use join:

{% set p = (year, month, day, post.slug)|join("/") %}
Answered By: mechanical_meat

Jinja2 also defines the ~ operator, which automatically converts arguments to string first, as an alternative to the + operator.

Example:

{% set p = year ~ '/' ~ month ~ '/' ~ day ~ '/' ~ post.slug %}

See Other operators or, if you really want to use str, modify the Environment.globals dictionary.

Answered By: Garrett

To cast to a string in an expression, you use x|string() instead of str(x).

string() is an example of a filter, and there are several useful filters that are worth learning about.

Answered By: FoxyLad
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.