Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 75 lines (60 sloc) 2.438 kB
a3c9494 @mitsuhiko Moved templating stuff into a separate module
authored
1 # -*- coding: utf-8 -*-
2 """
3 flask.templating
4 ~~~~~~~~~~~~~~~~
5
6 Implements the bridge to Jinja2.
7
8 :copyright: (c) 2010 by Armin Ronacher.
9 :license: BSD, see LICENSE for more details.
10 """
11 from jinja2 import BaseLoader, FileSystemLoader, TemplateNotFound
12
13 from flask.globals import _request_ctx_stack
14
15
16 class _DispatchingJinjaLoader(BaseLoader):
17 """A loader that looks for templates in the application and all
18 the module folders.
19 """
20
21 def __init__(self, app):
22 self.app = app
23
24 def get_source(self, environment, template):
25 name = template
26 loader = None
27 try:
28 module, name = template.split('/', 1)
29 loader = self.app.modules[module].jinja_loader
30 except (ValueError, KeyError):
31 pass
32 if loader is None:
33 loader = self.app.jinja_loader
34 try:
35 return loader.get_source(environment, name)
36 except TemplateNotFound:
37 # re-raise the exception with the correct fileame here.
38 # (the one that includes the prefix)
39 raise TemplateNotFound(template)
40
41 def list_templates(self):
42 result = self.app.jinja_loader.list_templates()
43 for name, module in self.app.modules.iteritems():
44 if module.jinja_loader is not None:
45 for template in module.jinja_loader.list_templates():
46 result.append('%s/%s' % (name, template))
47 return result
48
49
50 def render_template(template_name, **context):
51 """Renders a template from the template folder with the given
52 context.
53
54 :param template_name: the name of the template to be rendered
55 :param context: the variables that should be available in the
56 context of the template.
57 """
58 ctx = _request_ctx_stack.top
59 ctx.app.update_template_context(context)
60 return ctx.app.jinja_env.get_template(template_name).render(context)
61
62
63 def render_template_string(source, **context):
64 """Renders a template from the given template source string
65 with the given context.
66
67 :param template_name: the sourcecode of the template to be
68 rendered
69 :param context: the variables that should be available in the
70 context of the template.
71 """
72 ctx = _request_ctx_stack.top
73 ctx.app.update_template_context(context)
74 return ctx.app.jinja_env.from_string(source).render(context)
Something went wrong with that request. Please try again.