Skip to content

Instantly share code, notes, and snippets.

@anumsh
Last active September 15, 2016 01:57
Show Gist options
  • Save anumsh/2b34d5abd39c5ca8f1d66f72d98a78ab to your computer and use it in GitHub Desktop.
Save anumsh/2b34d5abd39c5ca8f1d66f72d98a78ab to your computer and use it in GitHub Desktop.
Introducing Template - templates.py file
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: templates.app
libraries:
- name: jinja2
version: latest
<form>
<h2>Add a food </h2>
<input type="text" name="food">
<button>Add</button>
</form>
import os
import jinja2
import webapp2
template_dir = os.path.join(os.path.dirname(templates.py), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir))
form_html = """
<form>
<h2>Add a food </h2>
<input type="text" name="food">
%s
<button>Add</button>
</form>
"""
hidden_html = """
<input type="hidden" name="food" value="%s">
"""
hidden_item = "<li> %s </li>"
shopping_list_html = """
<br>
<br>
<h2>Shopping List</h2>
<ul>
%s
</ul>
"""
class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
class MainPage(Handler):
def get(self):
output = form_html
output_hidden = ""
items = self.request.get_all("food")
print "the items are ", items
if items:
output_items = ""
for item in items:
output_hidden += hidden_html % item
output_items += hidden_item % item
output_shopping = shopping_list_html % output_items
output += output_shopping
output = output % output_hidden
self.write(output)
app = webapp2.WSGIApplication([('/', MainPage),
],
debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment