Reputation: 211
I am trying to nest tornado templates using {% include %}:
<html>
{% for headline in HL['headlines'] %}
{% include 'hl_1.html' %}
{% end %}
</ul>
</body>
</html>
The template above works, and the sub-template above works. What I cannot figure out how to do is pass in the name of the sub-template (e.g.replacing 'hl_1.html' with a string parameter in the parent template's namespace). AFter reviewing the template.py source code it seems that {% include accepts a string and nothing else. But it would be fantastic if one could dynamically specify sub-templates.
Has anyone tried this and succeeded?
thanks
Upvotes: 1
Views: 1656
Reputation: 5411
The way this is achieved usually is by using UI modules.
This is how I would structure your app.
First main.py
:
import tornado.ioloop
import tornado.web
import views
class MainHandler(tornado.web.RequestHandler):
def get(self):
HL = {
'headlines': ['head1', 'head2', 'head3'],
}
self.render('tmpl.html', HL=HL)
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
], ui_modules=views)
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Then your template tmpl.html
:
<html>
{% for headline in HL['headlines'] %}
{% module Headline(headline) %}
{% end %}
</ul>
</body>
</html>
Finally, views.py
, where you can define all your UI modules:
from tornado.web import UIModule
class Headline(UIModule):
def render(self, name):
return '<h1>%s</h1>' % name
UI modules
are like "reusable templates", that accept parameters.
Upvotes: 2