Changes between Version 3 and Version 4 of Ticket #35735
- Timestamp:
- Sep 5, 2024, 1:22:01 PM (3 months ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
Ticket #35735 – Description
v3 v4 3 3 class MyClass: 4 4 in_template = True 5 do_not_call_in_templates = True # prevent instantiation 6 7 @classmethod 8 def render_all_objects(cls): 9 ... 5 10 }}} 6 you could access the class property in the template through (if it was returned by a callable) `{{ get_my_class.in_template}}`.11 you could access the class property in the template through (if it was contained in the context) `{{ MyClass.in_template }}` or `{{ MyClass. render_all_objects }}`. 7 12 8 The template system first executes the callable `get_my_class` which we assume returns `MyClass`. Then it checks if the class is subscriptable (i.e. tries `MyClass["in_template"]`), will fail and then will get the in_template property.13 The template system first gets the class `MyClass` (and does not instantiate it) or gets it as a result of a callable `get_my_class`. Then it checks if the class is subscriptable (i.e. tries `MyClass["in_template"]`), will fail and then will get the in_template property. 9 14 10 As of python 3.9 some classes actually are subscriptable and trying to get the item will not fail: Typing shortcuts introduced syntax like `list[int]`. These hide class properties from the template system.15 As of python 3.9 some classes actually are subscriptable and trying to get the item will not fail: Typing shortcuts introduced syntax like `list[int]`. These hide class properties or methods from the template system. 11 16 12 17 Here's a test (that might go into tests/template_tests/syntax_tests/tests_basic.py) which passes on Python 3.9 and fails on Python 3.10+: … … 16 21 class MyClass(list): 17 22 in_template = True 23 do_not_call_in_templates = True # prevent instantiation 18 24 19 def get_my_class(): 20 return MyClass 21 22 # Pass the callable to return the class, or it would be resolved by the template 23 # engine 24 output = self.engine.render_to_string( 25 "basic-syntax19b", 26 {"klass": get_my_class} 27 ) 25 output = self.engine.render_to_string("basic-syntax19b", {"klass": MyClass}) 28 26 self.assertEqual(output, "True") 29 27 }}}