2012-03-24 32 views
20

我想投一個int通過url傳遞給模板,但它說str函數沒有被定義。鑄造inja到strin in Jinja2

我該如何解決這個問題?

這裏是我的代碼:

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

回答

25

的Jinja2還定義了~運營商,它首先會自動轉換參數字符串,作爲替代+運營商。

例子:

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

Other operators或者,如果你真的想用str,修改Environment.globals字典。

+1

這只是讓我失望。當我使用它時,Jinja2變得越來越棒。 – vectorfrog 2015-03-24 14:46:42

4

您可以使用join

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

要投射到表達式中的字符串,您可以使用x|string()而不是str(x)

string()是一個過濾器的例子,有幾個有用的過濾器,值得我們去學習。