pallets / jinja

A very fast and expressive template engine.

Home Page:https://jinja.palletsprojects.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Native types in macros works for list but does not work for int

AndreKR opened this issue · comments

#1511 by @mkrizek added a test that looks like this (formatting mine):

{%- macro x() -%}
  {{- [1,2] -}}
{%- endmacro -%}
{{- x()[1] -}}

This shows that rendering [1,2] in the macro returns an actual list from the macro, not a string.

According to the first example on https://jinja.palletsprojects.com/en/3.1.x/nativetypes/ I would expect this to work as well:

{%- macro x(a,b) -%}
  {{- a + b -}}
{%- endmacro -%}
{{- x(1,2) > 3 -}}

I would expect the macro to return an int, but apparently it returns a string.

Environment:

  • Python version: 3.11.6
  • Jinja version: 3.1.3

but apparently it returns a string.

The expression x(1,2) > 3 is a boolean expression and as such should return a boolean which indeed it does:

>>> from jinja2.nativetypes import NativeEnvironment
>>> r = NativeEnvironment().from_string("{%- macro x(a,b) -%}{{- a + b -}}{%- endmacro -%}{{- x(1,2) > 3 -}}").render()
>>> r, type(r)
(False, <class 'bool'>)

If the macro returned a string there would be an error like TypeError: '>' not supported between instances of 'str' and 'int'. Can you clarify why you think the macro returns a string?

Or maybe #1701 is related to your issue?

Hm, indeed, that code works when I try it in another Jinja2 playground. I was using it in the Template editor in Home Assistant, where it does in fact give the error you mention:

image

So there must be something special about the environment there.