Coverage for /home/runner/work/viur-core/viur-core/viur/src/viur/core/render/html/utils.py: 0%

33 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-03 13:41 +0000

1import typing as t 

2 

3__jinjaGlobals_ = {} 

4__jinjaFilters_ = {} 

5__jinjaTests_ = {} 

6__jinjaExtensions_ = [] 

7 

8 

9def getGlobalFunctions(): 

10 return __jinjaGlobals_ 

11 

12 

13def getGlobalFilters(): 

14 return __jinjaFilters_ 

15 

16 

17def getGlobalTests(): 

18 return __jinjaTests_ 

19 

20 

21def getGlobalExtensions(): 

22 return __jinjaExtensions_ 

23 

24 

25def jinjaGlobalFunction(f): 

26 """ 

27 Decorator, marks a function as a Jinja2 global. 

28 """ 

29 __jinjaGlobals_[f.__name__] = f 

30 return f 

31 

32 

33def jinjaGlobalFilter(f): 

34 """ 

35 Decorator, marks a function as a Jinja2 filter. 

36 """ 

37 __jinjaFilters_[f.__name__] = f 

38 return f 

39 

40 

41def jinjaGlobalTest(func_or_alias: t.Callable | str) -> t.Callable: 

42 """ 

43 Decorator, marks a function as a Jinja2 test. 

44 

45 To avoid name conflicts you can call the decorator 

46 with an alias as first argument. 

47 Otherwise, the test will be registered under the function name. 

48 

49 .. code-block:: python 

50 

51 # Example: 

52 from viur.core.render.html import jinjaGlobalTest 

53 # @jinjaGlobalTest # available under "positive_number" 

54 

55 @jinjaGlobalTest("positive") # available under "positive" 

56 def positive_number(render, value): 

57 return isinstance(value, int) and value > 0 

58 """ 

59 

60 if callable(func_or_alias): # is func 

61 __jinjaTests_[func_or_alias.__name__] = func_or_alias 

62 return func_or_alias 

63 

64 elif isinstance(func_or_alias, str): # is alias 

65 def wrapper(func): 

66 __jinjaTests_[func_or_alias] = func 

67 return func 

68 

69 return wrapper 

70 

71 else: 

72 raise TypeError( 

73 f"jinjaGlobalTest must be called with a function (used as decorator) " 

74 f"or a string (alias). But got {type(func_or_alias)}." 

75 ) 

76 

77 

78def jinjaGlobalExtension(ext): 

79 """ 

80 Function for activating extensions in Jinja2. 

81 """ 

82 if ext not in __jinjaExtensions_: 

83 __jinjaExtensions_.append(ext) 

84 return ext