Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

edit

  • Loading branch information...
commit 1bf51f12c66c577cda842b01d160c605a572dd04 1 parent 7df385a
Bibby authored anandology committed
Showing with 34 additions and 2 deletions.
  1. +34 −2 cookbook/template_jinja.md
View
36 cookbook/template_jinja.md
@@ -8,7 +8,7 @@ title: Use Jinja2 template engine in webpy
### Problem
How to use Jinja2 (http://jinja.pocoo.org/2/) template engine in webpy?
-### Solution
+### Solution 1
You need to install both Jinja2 and webpy(0.3) first, and then try out the following code snippet:
@@ -41,4 +41,36 @@ You need to install both Jinja2 and webpy(0.3) first, and then try out the follo
### Template file: templates/hello.html
- Hello, {{ name }}.
+ Hello, {{ name }}.
+
+### Solution 2
+
+With this solution, you have to specify template name, it's useful if template files are organized in different directories.
+
+ import os
+ import web
+ from jinja2 import Environment,FileSystemLoader
+
+ urls = ("/.*", "hello")
+ app = web.application(urls, globals())
+
+ def render_template(template_name, **context):
+ extensions = context.pop('extensions', [])
+ globals = context.pop('globals', {})
+
+ jinja_env = Environment(
+ loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')),
+ extensions=extensions,
+ )
+ jinja_env.globals.update(globals)
+
+ #jinja_env.update_template_context(context)
+ return jinja_env.get_template(template_name).render(context)
+
+ class hello:
+ def GET(self):
+ # You can use a relative path as template name, for example, 'ldap/hello.html'.
+ return render_template('hello.html', name='world',)
+
+ if __name__ == "__main__":
+ app.run()
Please sign in to comment.
Something went wrong with that request. Please try again.