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

后端 未结 13 1014
天命终不由人
天命终不由人 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}
    
    0 讨论(0)
  • 2020-11-29 16:43

    Google AppEngine uses the Django templating engine, have you taken a look at how they do it? You could possibly just use that.

    0 讨论(0)
  • 2020-11-29 16:45

    Don't. Use StringTemplate instead--there is no reason to consider any other template engine once you know about it.

    0 讨论(0)
  • 2020-11-29 16:47

    According to the Jinja documentation, Python 3 support is still experimental. So if you are on Python 3 and performance is not an issue, you can use django's built in template engine.

    Django 1.8 introduced support for multiple template engines which requires a change to the way templates are initialized. You have to explicitly configure settings.DEBUG which is used by the default template engine provided by django. Here's the code to use templates without using the rest of django.

    from django.template import Template, Context
    from django.template.engine import Engine
    
    from django.conf import settings
    settings.configure(DEBUG=False)
    
    template_string = "Hello {{ name }}"
    template = Template(template_string, engine=Engine())
    context = Context({"name": "world"})
    output = template.render(context) #"hello world"
    
    0 讨论(0)
  • 2020-11-29 16:49

    Found this:

    http://snippets.dzone.com/posts/show/3339

    0 讨论(0)
  • 2020-11-29 16:52

    Jinja2 syntax is pretty much the same as Django's with very few differences, and you get a much more powerfull template engine, which also compiles your template to bytecode (FAST!).

    I use it for templating, including in Django itself, and it is very good. You can also easily write extensions if some feature you want is missing.

    Here is some demonstration of the code generation:

    >>> import jinja2
    >>> print jinja2.Environment().compile('{% for row in data %}{{ row.name | upper }}{% endfor %}', raw=True) 
    from __future__ import division
    from jinja2.runtime import LoopContext, Context, TemplateReference, Macro, Markup, TemplateRuntimeError, missing, concat, escape, markup_join, unicode_join
    name = None
    
    def root(context, environment=environment):
        l_data = context.resolve('data')
        t_1 = environment.filters['upper']
        if 0: yield None
        for l_row in l_data:
            if 0: yield None
            yield unicode(t_1(environment.getattr(l_row, 'name')))
    
    blocks = {}
    debug_info = '1=9'
    
    0 讨论(0)
提交回复
热议问题