【问题标题】:casting ints to str in Jinja2在 Jinja2 中将整数转换为 str
【发布时间】:2012-04-09 00:55:45
【问题描述】:

我想转换一个通过 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 %}

【问题讨论】:

    标签: python jinja2


    【解决方案1】:

    您可以使用join:

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

    【讨论】:

      【解决方案2】:

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

      例子:

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

      请参阅Other operators,或者,如果您真的想使用str,请修改Environment.globals 字典。

      【讨论】:

      • 这让我大吃一惊。随着我使用 Jinja2,它变得越来越棒。
      【解决方案3】:

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

      string() 是一个过滤器示例,there are several useful filters 值得学习。

      【讨论】:

        猜你喜欢
        • 2013-03-01
        • 2020-07-23
        • 2021-05-05
        • 2014-04-03
        • 2015-09-26
        • 2018-06-07
        • 1970-01-01
        • 1970-01-01
        • 2011-10-27
        相关资源
        最近更新 更多