将int转换为Jinja2中的str [英] casting ints to str in Jinja2

查看:695
本文介绍了将int转换为Jinja2中的str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换一个通过URL传递给模板的int,但是它表示未定义str函数.

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.

我该如何解决?

这是我的代码:

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

推荐答案

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

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

示例:

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

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

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

这篇关于将int转换为Jinja2中的str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆