Skip to content

Commit

Permalink
added example for Jinja2 templating (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobbridges authored and jabridges committed Feb 9, 2017
1 parent 82af698 commit 3661725
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
9 changes: 9 additions & 0 deletions examples/8_html/html.py
@@ -1,5 +1,6 @@
# examples/8_html/html.py
from japronto import Application
from jinja2 import Template


# A view can read HTML from a file
Expand All @@ -13,12 +14,20 @@ def example(request):
return request.Response(text='<h1>Some HTML!</h1>', mime_type='text/html')


# A view could also return a rendered jinja2 template
def jinja(request):
template = Template('<h1>Hello {{ name }}!</h1>')
return request.Response(text=template.render(name='World'),
mime_type='text/html')


# Create the japronto application
app = Application()

# Add routes to the app
app.router.add_route('/', index)
app.router.add_route('/example', example)
app.router.add_route('jinja2', jinja)

# Start the server
app.run(debug=True)
Expand Down
11 changes: 10 additions & 1 deletion tutorial/8_html.md
@@ -1,12 +1,13 @@
# Responding with HTML

Serving HTML from japronto is as simple as adding a MIME type of `text/html` to the Response.
Serving HTML from japronto is as simple as adding a MIME type of `text/html` to the Response. Jinja2 templating can be leveraged as well, although in the meantime you will have to do the heavy lifting of rendering templates before sending in a response.

Copy and paste following code into a file named `html.py`:

```python
# examples/8_html/html.py
from japronto import Application
from jinja2 import Template


# A view can read HTML from a file
Expand All @@ -20,12 +21,20 @@ def example(request):
return request.Response(text='<h1>Some HTML!</h1>', mime_type='text/html')


# A view could also return a rendered jinja2 template
def jinja(request):
template = Template('<h1>Hello {{ name }}!</h1>')
return request.Response(text=template.render(name='World'),
mime_type='text/html')


# Create the japronto application
app = Application()

# Add routes to the app
app.router.add_route('/', index)
app.router.add_route('/example', example)
app.router.add_route('jinja2', jinja)

# Start the server
app.run(debug=True)
Expand Down

0 comments on commit 3661725

Please sign in to comment.