在Jinja2中投入到str

Mah*_*sam 29 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 %}
Run Code Online (Sandbox Code Playgroud)

Gar*_*ett 36

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

例:

{% set p = year ~ '/' ~ month ~ '/' ~ day ~ '/' ~ post.slug %}
Run Code Online (Sandbox Code Playgroud)

请参阅其他运算符,或者,如果您确实要使用str,请修改Environment.globals字典.

  • 这真让我震惊。当我使用Jinja2时,它变得越来越出色。 (2认同)

Fox*_*Lad 16

要转换为表达式中的字符串,请使用x|string()而不是str(x).

string() 是一个过滤器的例子,有几个有用的过滤器值得学习.