Skip to content

Instantly share code, notes, and snippets.

@wolever
Created April 6, 2014 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolever/10011815 to your computer and use it in GitHub Desktop.
Save wolever/10011815 to your computer and use it in GitHub Desktop.
Shows how to render a Django template using a custom template tag library.
from django.conf import settings as s
from django.template import Parser, Lexer, Context, Library, StringOrigin
lib = Library()
def parse_template(library, origin, template_string):
if s.TEMPLATE_DEBUG:
from django.template.debug import DebugLexer, DebugParser
lexer_class, parser_class = DebugLexer, DebugParser
else:
lexer_class, parser_class = Lexer, Parser
lexer = lexer_class(template_string, StringOrigin(origin))
parser = parser_class(lexer.tokenize())
parser.add_library(library)
return parser.parse()
@lib.filter_function
def say_hello(value):
return "Hello, %s" %(value, )
my_template = parse_template(lib, "some_template_name", """
{{ name|say_hello }}
""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment