[Twisted-web] Twisted.Web and Jinja2
Lucas Taylor
ltaylor.volks at gmail.com
Wed Jun 19 12:35:08 MDT 2013
On Jun 18, 2013, at 8:47 PM, Jo as Queeniebee wrote:
> Hello,
>
> I'm writing a content server to run on my Raspberry Pi and I'll be using Jinja2 as the templating engine. I'm new to Twisted so I'm having a hard time imaging the examples for TwistedMatrix.com scale.
>
> Are there any examples of a fully featured Twisted application that uses Jinja2 or any other templating engine like Mako?
Hi Jo,
You can return a string (e.g. a rendered jinja2 template) from the .render method of an IResource
http://twistedmatrix.com/documents/current/web/howto/using-twistedweb.html#auto6
So when you see a string being returned from a Resource in the docs, you can consider substituting the particulars of the template engine you want to use.
Here's a very simple example of one approach using jinja2:
## myapp/config.py
#
# Define a jinja2 Environment somewhere
# I specify a PackageLoader to look up templates from the templates folder in the myapp.web.static package
from jinja2 import Environment, PackageLoader
jinja = Environment(loader=PackageLoader('myapp.web.static', 'templates'))
----
## myapp/web/views.py
#
from twisted.web.resource import Resource
from myapp.config import jinja
class MyResource(Resource):
isLeaf = True
template_name = "example.html"
def render_GET(self, request):
ctx = {
'content': "Templated content",
'extra_info': [1, 2, 3, 4, 5, 6]
}
template = jinja.get_template(self.template_name)
return template.render(ctx)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://twistedmatrix.com/pipermail/twisted-web/attachments/20130619/94f1c709/attachment.html>
More information about the Twisted-web
mailing list