casting ints to str in Jinja2

前端 未结 3 1988
日久生厌
日久生厌 2020-12-29 02:44

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.

How do I get around this?

<
相关标签:
3条回答
  • 2020-12-29 03:14

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

    Example:

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

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

    0 讨论(0)
  • 2020-12-29 03:27

    To cast to a string in an expression, you use x|string() instead of str(x).

    string() is an example of a filter, and there are several useful filters that it's worth learning about.

    0 讨论(0)
  • 2020-12-29 03:34

    You may use join:

    {% set p = (year, month, day, post.slug)|join("/") %}
    
    0 讨论(0)
提交回复
热议问题