Debian Codegraph @

django_jinja/library.py

raw symbols SCIP
1 import functools
2
3 from django.template.loader import render_to_string
4 from django.utils.safestring import mark_safe
5
6
7 # Global register dict for third party
8 # template functions, filters and extensions.
9 _local_env = {
10 "globals": {},
11 "tests": {},
12 "filters": {},
13 "extensions": set(),
14 }
15
16
17 def _update_env(env):
18 """
19 Given a jinja environment, update it with third party
20 collected environment extensions.
21 """
22
23 env.globals.update(_local_env["globals"])
24 env.tests.update(_local_env["tests"])
25 env.filters.update(_local_env["filters"])
26
27 for extension in _local_env["extensions"]:
28 env.add_extension(extension)
29
30
31 def _attach_function(attr, func, name=None):
32 if name is None:
33 name = func.__name__
34
35 global _local_env
36 _local_env[attr][name] = func
37 return func
38
39
40 def _register_function(attr, name=None, fn=None):
41 if name is None and fn is None:
42 def dec(func):
43 return _attach_function(attr, func)
44 return dec
45
46 elif name is not None and fn is None:
47 if callable(name):
48 return _attach_function(attr, name)
49 else:
50 def dec(func):
51 return _register_function(attr, name, func)
52 return dec
53
54 elif name is not None and fn is not None:
55 return _attach_function(attr, fn, name)
56
57 raise RuntimeError("Invalid parameters")
58
59
60 def extension(extension):
61 global _local_env
62 _local_env["extensions"].add(extension)
63 return extension
64
65
66 def global_function(*args, **kwargs):
67 return _register_function("globals", *args, **kwargs)
68
69
70 def test(*args, **kwargs):
71 return _register_function("tests", *args, **kwargs)
72
73
74 def filter(*args, **kwargs):
75 return _register_function("filters", *args, **kwargs)
76
77
78 def render_with(template, fn=None):
79 """
80 Makes simple function works like
81 django's default inclusion_tag: render
82 specified template with context returned
83 by decorated function.
84 """
85
86 if fn is None:
87 return functools.partial(render_with, template)
88
89 @functools.wraps(fn)
90 def _wrapper(*args, **kwargs):
91 data = render_to_string(template, fn(*args, **kwargs))
92 return mark_safe(data)
93
94 return _wrapper