Skip to content

Commit 85dd4f1

Browse files
EnotShowaminalaee
andauthored
Update template engine environment docs (aminalaee#703)
Co-authored-by: Amin Alaee <mohammadamin.alaee@gmail.com>
1 parent 0e132da commit 85dd4f1

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

docs/working_with_templates.md

+78
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,81 @@ SQLAdmin and in the `content` block it adds custom HTML tags:
2525
class UserAdmin(ModelView, model=User):
2626
details_template = "custom_details.html"
2727
```
28+
29+
## Customizing Jinja2 environment
30+
31+
You can add custom environment options to use it on your custom templates. First set up a project:
32+
33+
```python
34+
from sqladmin import Admin
35+
from starlette.applications import Starlette
36+
37+
38+
app = Starlette()
39+
admin = Admin(app, engine)
40+
```
41+
42+
Then you can add your environment options:
43+
44+
### Adding filters
45+
46+
```python
47+
def datetime_format(value, format="%H:%M %d-%m-%y"):
48+
return value.strftime(format)
49+
50+
admin.templates.env.filters["datetime_format"] = datetime_format
51+
```
52+
53+
Usage in templates:
54+
55+
```
56+
{{ article.pub_date|datetimeformat }}
57+
{{ article.pub_date|datetimeformat("%B %Y") }}
58+
```
59+
60+
### Adding tests
61+
62+
```python
63+
import math
64+
65+
def is_prime(n):
66+
if n == 2:
67+
return True
68+
69+
for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
70+
if n % i == 0:
71+
return False
72+
73+
return True
74+
75+
admin.templates.env.tests["prime"] = is_prime
76+
```
77+
78+
Usage in templates:
79+
80+
```
81+
{% if value is prime %}
82+
{{ value }} is a prime number
83+
{% else %}
84+
{{ value }} is not a prime number
85+
{% endif %}
86+
```
87+
88+
# Adding globals
89+
90+
```python
91+
def value_is_filepath(value: Any) -> bool:
92+
return isinstance(value, str) and os.path.isfile(value)
93+
94+
admin.templates.env.globals["value_is_filepath"] = value_is_filepath
95+
```
96+
97+
Usage in templates:
98+
99+
```
100+
{% if value_is_filepath(value) %}
101+
{{ value }} is file path
102+
{% else %}
103+
{{ value }} is not file path
104+
{% endif %}
105+
```

0 commit comments

Comments
 (0)