How do I use Django templates without the rest of Django?

后端 未结 13 1015
天命终不由人
天命终不由人 2020-11-29 16:17

I want to use the Django template engine in my (Python) code, but I\'m not building a Django-based web site. How do I use it without having a settings.py file (and others)

相关标签:
13条回答
  • 2020-11-29 17:06

    The solution is simple. It's actually well documented, but not too easy to find. (I had to dig around -- it didn't come up when I tried a few different Google searches.)

    The following code works:

    >>> from django.template import Template, Context
    >>> from django.conf import settings
    >>> settings.configure()
    >>> t = Template('My name is {{ my_name }}.')
    >>> c = Context({'my_name': 'Daryl Spitzer'})
    >>> t.render(c)
    u'My name is Daryl Spitzer.'
    

    See the Django documentation (linked above) for a description of some of the settings you may want to define (as keyword arguments to configure).

    0 讨论(0)
提交回复
热议问题