Created
April 6, 2014 21:47
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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