2012-03-24 21 views
20

Voglio eseguire il cast di un int che viene passato al modello tramite l'url, ma che la funzione str non è definita.casting da Jinja2

Come aggirare questo?

Ecco il mio codice:

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

risposta

25

Jinja2 definisce anche l'operatore ~, che converte automaticamente gli argomenti di stringa di prima, in alternativa all'operatore +.

Esempio:

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

Vedi Other operators o, se si vuole veramente utilizzare str, modificare il dizionario Environment.globals.

+1

Questo mi ha fatto impazzire. Jinja2 diventa sempre più fantastico mentre lavoro con esso. – vectorfrog

4

È possibile utilizzare join:

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

Per eseguire il cast su una stringa in un'espressione, utilizzare x|string() anziché str(x).

string() è un esempio di filtro e ci sono diversi filtri utili che vale la pena conoscere.