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

后端 未结 13 1054
天命终不由人
天命终不由人 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 16:42

    Thanks for the help folks. Here is one more addition. The case where you need to use custom template tags.

    Let's say you have this important template tag in the module read.py

    from django import template
    
    register = template.Library()
    
    @register.filter(name='bracewrap')
    def bracewrap(value):
        return "{" + value + "}"
    

    This is the html template file "temp.html":

    {{var|bracewrap}}
    

    Finally, here is a Python script that will tie to all together

    import django
    from django.conf import settings
    from django.template import Template, Context
    import os
    
    #load your tags
    from django.template.loader import get_template
    django.template.base.add_to_builtins("read")
    
    # You need to configure Django a bit
    settings.configure(
        TEMPLATE_DIRS=(os.path.dirname(os.path.realpath(__file__)), ),
    )
    
    #or it could be in python
    #t = Template('My name is {{ my_name }}.')
    c = Context({'var': 'stackoverflow.com rox'})
    
    template = get_template("temp.html")
    # Prepare context ....
    print template.render(c)
    

    The output would be

    {stackoverflow.com rox}
    

提交回复
热议问题