在Jinja2中投入到str

时间:2012-03-24 23:23:21

标签: python jinja2

我想要转换一个通过url传递给模板的int,但是它表示没有定义str函数。

我该如何解决这个问题?

这是我的代码:

{% 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 %}

3 个答案:

答案 0 :(得分:33)

Jinja2还定义了~运算符,它首先自动将参数转换为字符串,作为+运算符的替代。

示例:

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

请参阅Other operators,或者,如果您确实想使用str,请修改Environment.globals词典。

答案 1 :(得分:15)

要转换为表达式中的字符串,请使用x|string()代替str(x)

string()是过滤器的一个示例,有几个有用的过滤器值得了解。

答案 2 :(得分:4)

您可以使用join

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