Better way to bring in tags automatically for Jinja2 templating?

32 views
Skip to first unread message

Benjamin Schollnick

unread,
May 4, 2021, 9:10:47 PM5/4/21
to django...@googlegroups.com
I'm not sure there is a better way to do this?

But I am using the Jinja2 templating engine with Django, and I originally set this up in Django2-ish?
So maybe I missed a better way to do this...

So I have a jinjaenv.py file that simply setups up the environment for the Jinja2 template engine.

jinjaenv.py
```
#from __future__ import absolute_import # Python 2 only
from jinja2 import Environment
from django.contrib.staticfiles.storage import staticfiles_storage
from django.urls import reverse
from django_icons.templatetags.icons import icon

def environment(**options):
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
'icon':icon,
})
return env
```
And have that in my settings:

# https://docs.djangoproject.com/en/2.1/ref/templates/api/#django.template.loaders.cached.Loader

{ 'NAME': "Jinja2",
"BACKEND": "django_jinja.backend.Jinja2",
"APP_DIRS": True,
'DIRS': [TEMPLATE_PATH,],
"OPTIONS": {'environment': "quickbbs.jinjaenv.environment",
# Match the template names ending in .html but not the ones in the admin folder.
"match_extension": ".jinja",
"extensions": [
"jinja2.ext.do",
"jinja2.ext.loopcontrols",
"jinja2.ext.with_",
"jinja2.ext.i18n",
"jinja2.ext.autoescape",
"django_jinja.builtins.extensions.CsrfExtension",
"django_jinja.builtins.extensions.CacheExtension",
"django_jinja.builtins.extensions.TimezoneExtension",
"django_jinja.builtins.extensions.UrlsExtension",
"django_jinja.builtins.extensions.StaticFilesExtension",
"django_jinja.builtins.extensions.DjangoFiltersExtension",
],
"bytecode_cache": {
"name": "default",
"backend": "django_jinja.cache.BytecodeCache",
"enabled": True,
},
"autoescape": True,
"auto_reload": True,
"translation_engine": "django.utils.translation",
}
},

Is there a better way to do this? It’s a pain to update the environment file…
And I can’t tell if the django-icon issue that I’m seeing is due to Jinja2 or not.
(I’m 99% sure it isn’t… But)

- Benjamin

Reply all
Reply to author
Forward
0 new messages