Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

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

Closed
AndreKR opened this issue Feb 4, 2024 · 2 comments
Closed

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

AndreKR opened this issue Feb 4, 2024 · 2 comments

Comments

@AndreKR
Copy link

AndreKR commented Feb 4, 2024

#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
@mkrizek
Copy link
Contributor

mkrizek commented Feb 5, 2024

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?

@AndreKR
Copy link
Author

AndreKR commented Feb 5, 2024

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.

@davidism davidism closed this as completed Feb 5, 2024
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Feb 20, 2024
# for free to subscribe to this conversation on GitHub. Already have an account? #.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants